Spring Boot Send Http Request

透過HttpPost 並以JSON格式傳送

Java
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;

String url = "request link";
HttpPost hp = new HttpPost(url);

//以form 形式傳遞
List<NameValuePair> urlParameters = new ArrayList<>();
urlParameters.add(new BasicNameValuePair("value1", value1));
urlParameters.add(new BasicNameValuePair("value2", value2));

hp.setEntity(new UrlEncodedFormEntity(urlParameters));

//以json 形式傳遞
String sendJson = "{" +
  "\"value1\": \"" + value1 + "\"," +
  "\"value2\": \"" + value2 + "\"" +
  "}";
StringEntity se = new StringEntity(sendJson);

hp.setEntity(se);

//設定header
hp.setHeader(new BasicHeader("Content-Type", "application/json; charset=UTF-8")); //視乎你用哪種方式傳遞,這裡以json作例子
hp.setHeader(new BasicHeader("Accept", "text/plain; charset=UTF-8"));

try(CloseableHttpClient httpClient = HttpClients.createDefault();
    CloseableHttpResponse response = httpClient.execute(hp)) {
   System.out.println(EntityUtils.toString(response.getEntity()));  //取得回傳資料
}

開始在上面輸入您的搜索詞,然後按回車進行搜索。按ESC取消。

返回頂部