HttpUtils类抽取
新建一个HttpUtils类,抽取接口一些共性方法
封装响应体获取方法
public static String returnResponseBody(HttpResponse httpResponse) throws Exception, IOException {
Header[] allHeaders = httpResponse.getAllHeaders();
System.out.println("响应头:" + Arrays.toString(allHeaders));
HttpEntity httpEntity = httpResponse.getEntity();
String body = EntityUtils.toString(httpEntity);
System.out.println("响应体:" + body);
int statusCode = httpResponse.getStatusLine().getStatusCode();
System.out.println("响应码:" + statusCode);
return body;
}
封装get请求方法
当前初始封装版本还是把请求头放入方法中,可根据项目情况进行请求头抽取
public static void get(String url) throws Exception {
// 设置以get请求方式请求url,请求地址作为入参传递
HttpGet get = new HttpGet(url);
get.setHeader("请求头字段", "字段值");
HttpClient httpClient = HttpClients.createDefault();
HttpResponse httpResponse = httpClient.execute(get);
//获取响应体,调用已封装好的获取响应体方法
returnResponseBody(httpResponse);
}
封装post请求方法
public static void post(String url,String params) throws Exception {
HttpPost post = new HttpPost(url);
get.setHeader("请求头字段", "字段值");
//把请求入参作为params参数传递
post.setEntity(new StringEntity(params,"utf-8"));
HttpClient httpClient = HttpClients.createDefault();
HttpResponse httpResponse = httpClient.execute(post);
returnResponseBody(httpResponse);
}