88103756 2020-01-01
上代码干货,测试接口来源 http://www.httpbin.org/
import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import org.apache.http.HttpEntity; 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; import org.testng.annotations.Test; import java.io.IOException; public class HttpRequest { @Test public void httpGet() throws IOException { //创建client有两种途径,查看源码可知最终都是调用 HttpClientBuilder.create().build(); CloseableHttpClient client= HttpClients.createDefault(); //CloseableHttpClient client= HttpClients.custom().build(); //创建 get 对象, HttpGet get=new HttpGet("http://www.httpbin.org/get"); //设置 请求头 get.setHeader("Referer","http://www.httpbin.org/"); get.setHeader("accept","application/json"); // HttpGet还可以设置connectTimeout,socketTimeout等,使用 get.setConfig(); //获取响应 CloseableHttpResponse response=client.execute(get); HttpEntity entity=response.getEntity(); String result=EntityUtils.toString(entity); //关闭流,释放连接 EntityUtils.consume(entity); response.close(); //解析result,是json的话,可以使用 fastjson来解析 JSONObject resultJson= JSON.parseObject(result); System.out.println(resultJson.getString("headers")); } }
1. 设置请求头有两个方法:
httpGet.setHeader("key","value"); 设置一个请求头,有则覆盖,无则新增
httpGet.addHeader("key","value"); 添加一个新的请求头,允许有重复
2. 请求头常见的三种 content-type
application/x-www-form-urlencoded ,会将表单参数携带在url中进行传递,可以直接将参数用键=值&键=值的形式进行拼接到url中
application/json, 将参数以json格式进行传递
multiPart/form-data,混合表单,上传文件时使用
3. 关于 get.setConfig() ,其中的更多属性设置查看源码可知
结果
{"Accept":"application/json","Referer":"http://www.httpbin.org/","User-Agent":"Apache-HttpClient/4.5.3 (Java/1.8.0_231)","Host":"www.httpbin.org","Accept-Encoding":"gzip,deflate"}