Java中請求遠程接口方法
請求遠程接口方法
public static void postinit(PageData pd) throws Exception {
// 創建Httpclient對象
CloseableHttpClient httpclient = HttpClients.createDefault();
// 創建http POST請求
HttpPost httpPost = new HttpPost("你的遠程接口地址");
// 設置參數
List<NameValuePair> parameters = new ArrayList<NameValuePair>(0);
parameters.add(new BasicNameValuePair("type", pd.getString("type")));
parameters.add(new BasicNameValuePair("deviceCode", pd.getString("deviceCode")));
parameters.add(new BasicNameValuePair("gridCode", pd.getString("gridCode")));
// 構造一個form表單式的實體
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters);
// 將請求實體設置到httpPost對象中
httpPost.setEntity(formEntity);
httpPost.setHeader(
"User-Agent",
"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36");
CloseableHttpResponse response = null;
try {
// 執行請求
response = httpclient.execute(httpPost);
// 判斷返回狀態是否爲200
if (response.getStatusLine().getStatusCode() == 200) {
String content = EntityUtils.toString(response.getEntity(),
"UTF-8");
System.out.println("返回數據爲"+content);
}
} finally {
if (response != null) {
response.close();
}
httpclient.close();
}
}
其中Pagedate爲一個封裝的map類