1.使用httpclient
(1)//get方式
public static String doGet(String url,Map<String, String> param){
CloseableHttpClient httpClient = HttpClients.createDefault();
String resultString = "";
CloseableHttpResponse response = null;
try {
URIBuilder builder = new URIBuilder(url);
if(param!=null){
for(String key:param.keySet()){
builder.addParameter(key,param.get(key));
}
}
URI uri = builder.build();
HttpGet httpGet = new HttpGet(uri);
response = httpClient.execute(httpGet);
if(response.getStatusLine().getStatusCode()==200){
resultString = EntityUtils.toString(response.getEntity());
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
if(response!=null){
response.close();
}
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return resultString;
}
注意事项:
1.如果返回的是一个json对象,服务端的响应方法上要加@responsbody注解,否则获取的响应头中值为“”;
2.目标项目的ip和端口要写对,我写错端口号结果返回过来一个页面