Http远程调用两种方式:Get 和Post请求
这里适用HttpClient实现两种请求。
Get请求:
List
params.add(new BasicNameValuePair("name","hello"));
UrlEncodeFormEntity entity = new UrlEncodeFormEntity(params, HTTP.UTF.8);
String url = "localhost";
HttpGet request = new HttpGet(url + "?" + EntityUtils.toString(entity));
ResponseHandler
CloseableHttpClient httpClient = HttpClients.createDefault();
try{
requet.setHeader("Accept", "application/json");
String responseJson = httpClient.excute(request, handler);
} catch (IOException e){
e.printStackTrace();
} finally {
httpClient.getConnectionManager().closeExpiredConnections();
httpClient.getConnectionManager().closeIdleConnections(30 , TimeUtil.SECONDS);
}
Post请求:
List
params.add(new BasicNameValuePair("name","hello"));
UrlEncodeFormEntity entity = new UrlEncodeFormEntity(params, HTTP.UTF.8);
String url = "localhost";
HttpPost request = new HttpPost(url);
requet.setEntity(entity);
ResponseHandler
CloseableHttpClient httpClient = HttpClients.createDefault();
try{
requet.setHeader("Accept", "application/json");
String responseJson = httpClient.excute(request, handler);
} catch (IOException e){
e.printStackTrace();
} finally {
httpClient.getConnectionManager().closeExpiredConnections();
httpClient.getConnectionManager().closeIdleConnections(30 , TimeUtil.SECONDS);
}