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类