httpclient(二)

静下心看了一遍httpclient的api,我这英语水平看文档太费劲了,还好又有了很多新的收获,这里在记录下以免时间久了忘记了

官方API给出了httpclient的关键步骤,还是上节总结的  1、创建模拟浏览器2、创建请求3、得到相应结果

  通过HttpClients的静态方法createDefault创建返回一个CloseableHttpClient对象,也可以通过HttpClientBuilder类的builder方法创建 这种方式可以设置一些默认headers等信息

  CloseableHttpClient httpclient = HttpClients.createDefault();  

  HttpGet httpget = new HttpGet("http://localhost/");

  CloseableHttpResponse response = httpclient.execute(httpget);

1、请求

HttpPostt、HttpGet类有三种构造方法

HttpGet get = new HttpGet(); //下面两种比较常用
HttpGet get = new HttpGet(String url);  //传递一个url 上一节说过,相对比较容易理解
HttpGet get = new HttpGet( URI uri);//见下面的代码示例

httpclint提供了URIBuilder类通过.build()方法用来创建URI对象

URI url=new URIBuilder().setScheme("http")
                .setHost("127.0.0.1")
                .setPort(8989)
                .setPath("/login")
                .setParameter("username", "111111")//添加参数
                .setParameter("password", "111111")
          .setCustomQuery("username=111111&password=111111").build(); 
CloseableHttpClient httpclient = HttpClients.createDefault(); 
HttpPost post = new HttpPost(url);

 

2、响应

System.out.println(response.getProtocolVersion());  //HTTP/1.1
System.out.println(response.getStatusLine().getStatusCode()); //200
System.out.println(response.getStatusLine().getReasonPhrase()); //ok
System.out.println(response.getStatusLine().toString());//HTTP/1.1 200 OK

 3、头部信息

HttpPost和HttpResponse等都提供了删除添加headers的方法

get.addHeader("1","2");
post.addHeader("1","2");

4、实体Entity 

这里调用了StringEntity的构造方法把字符串转变成一个实体的对象,可以使用getContentType和getContentLength获取内容的类型和长度 通过EntityUtils.toString(entity)将内容转化成字符串---一般用于response结果的展示

StringEntity entity = new StringEntity("12345","utf-8");
entity.setContentType("text/json");             
entity.setContentEncoding("UTF-8");             
post.addHeader("Content-type", "application/json;charset=UTF-8");
post.setEntity(entity); //通过post对象的setEntity方法添加到post对象中

5、资源释放

  response.close()

  httpclient.close()

6、返回结果中实体内容的处理----Consuming entity content不知道翻译成啥

HttpEntity httpEntity = response.getEntity(); 
String result = EntityUtils.toString(httpEntity, "utf-8");

这里官方的文档是不建议使用EntityUtils的,不过我用到现在还没出现过问题,后续观察

7、添加内容到请求实体

 7.1文件

File file = new File("somefile.txt");
FileEntity entity = new FileEntity(file, ContentType.create("text/plain", "UTF-8"));
post.setEntity(entity);

  7.2form表单

List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("1","1"));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
post.setEntity(entity);

7.3字符串或者json上面第四点已经描述过,这里直接贴api例子

StringEntity entity = new StringEntity("important message",ContentType.create("plain/text", Consts.UTF_8));
entity.setChunked(true);
HttpPost httppost = new HttpPost("http://localhost/acrtion.do");
httppost.setEntity(entity);

 8、设置代理

设置代理涉及到三个类RequestConfig.Builder(RequestConfig的嵌套类)、HttpPost、HttpHost;RequestConfig.Builder用来配置一些外部的网络环境。使用时先用RequestConfig类的静态方法custom()获取equestConfig.Builder的配置器。

这里面常用的是配置代理proxy、连接超时时间等

HttpHost proxy = new HttpHost("127.0.0.1", 8888);
RequestConfig requestConfig =  RequestConfig.custom()
                          .setProxy(proxy)
                          .setConnectTimeout(10000)
                          .setSocketTimeout(10000)                     .setConnectionRequestTimeout(3000).build();

然后通过HttpPost的setConfig方法加到请求中

post.setConfig(requestConfig);

 

 

 

 

 

 

 

posted @ 2019-07-05 14:16  国际惯例  阅读(219)  评论(0编辑  收藏  举报