java 通过HTTPClient工具类发送请求
客户端code 如下:
package com.eas.bojoy;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class TestHttpClient {
public static void main(String[] args) {
// 1.获得一个HttpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
// 2.生成一个HttpGet请求
HttpGet httpGet = new HttpGet("http://localhost:8080/testSSM/depts");
CloseableHttpResponse response = null;
// 3.执行get请求
try {
response = httpClient.execute(httpGet);
} catch (IOException e1) {
e1.printStackTrace();
}
String result="";
HttpEntity entity = response.getEntity();
try {
if(entity != null)
result = EntityUtils.toString(entity);
} catch (ParseException | IOException e) {
e.printStackTrace();
}finally {
try {
if(response != null)
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("结果为:"+result);
}
}
服务端code如下:
@RequestMapping(value="/depts")
@ResponseBody
public Msg getDepts(){
List<Department> list = departmentService.getDepts();
return Msg.success().add("depts", list);
}
result结果如下:
还没有评论,来说两句吧...