zoukankan      html  css  js  c++  java
  • get请求

    上代码干货,测试接口来源  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() ,也可以在创建client时进行设置,有 ConnectionConfig,SocketConfig,RequestConfig;其中的更多属性设置查看源码可知,

      结果

    {"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"}
  • 相关阅读:
    修改msn密碼的地址
    Global.asax.cs中的方法的含义 Application_AcquireRequestState验证Session[轉]
    工作筆記DMIS項目
    给创业者的忠告
    Windows 2008 / Windows 7 x64: The ‘Microsoft.Jet.OLEDB.4.0′ provider is not registered on the local machine.
    Case Study: Nick Leeson and The Barings Debacle
    如何减小MS SQL Server的Log文件尺寸
    如何使windows7的默认共享可以被访问
    Android 开发人员必须掌握的 10 个开发工具
    在Windows Server 2008 R2上设置FTP 服务
  • 原文地址:https://www.cnblogs.com/yjh1995/p/12130921.html
Copyright © 2011-2022 走看看