• 使用httpclient发送get或post请求


    HttpClient 是 Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。当前官网最新版介绍页是:http://hc.apache.org/httpcomponents-client-4.5.x/index.html

    许多模拟http请求的框架都用httpclient,测试人员可通过它模拟请求http协议接口,做接口自动化测试。

    1、包下载:
    地址:http://mvnrepository.com/

            <!-- maven依赖 -->
            <dependency>
                <groupId>org.apache.httpcomponents</groupId>
                <artifactId>httpclient</artifactId>
                <version>4.5.2</version>
            </dependency>

    发送get请求

    1、通过请求参数url和头文件cookie作为参数(cookie可以为空)发送get请求,读取返回内容

    代码如下:

    public static String httpGet(String url,String cookie) throws Exception{  
    
            String result=""; //返回信息
            //创建一个httpGet请求
            HttpGet request=new HttpGet(url);
            //创建一个htt客户端
            @SuppressWarnings("resource")
            HttpClient httpClient=new DefaultHttpClient();
            //添加cookie到头文件
            request.addHeader("Cookie", cookie);
            //接受客户端发回的响应
            HttpResponse httpResponse=httpClient.execute(request);
            //获取返回状态
            int statusCode=httpResponse.getStatusLine().getStatusCode();
            if(statusCode==HttpStatus.SC_OK){
                //得到客户段响应的实体内容
                HttpEntity responseHttpEntity=httpResponse.getEntity();
                //得到输入流
                InputStream in=responseHttpEntity.getContent();
                //得到输入流的内容
                result=getData(in);
            }
            //Log.d(TAG, statusCode+"");
            return result;
        }

    2、有时候,当我们想获取返回头文件信息,而不是返回内容时,只需要修改:

          //获取返回状态
            int statusCode=httpResponse.getStatusLine().getStatusCode();
            if(statusCode==HttpStatus.SC_OK){
                //取头文件名(header值)信息
                strResult=httpResponse.getHeaders(header)[0].getValue().toString();
    //            Header[] headers = httpResponse.getAllHeaders();//返回的HTTP头信息
    //            for (int i=0; i<headers.length; i++) {
    //                System.out.println(headers[i]);
    //            }
            }

    发送post请求

    1、请求地址、请求参数(map格式)、请求cookie作为参数发送Post请求

    public static String httpPost(String url,Map<String,String> map,String cookie) {
            //返回body
            String body = "";  
            //1、创建一个htt客户端
            @SuppressWarnings("resource")
            HttpClient httpClient=new DefaultHttpClient();
            //2、创建一个HttpPost请求
            HttpPost response=new HttpPost(url);
            
            //3、设置参数
            //建立一个NameValuePair数组,用于存储欲传送的参数
            List<NameValuePair> params = new ArrayList<NameValuePair>();  
            if(map!=null){  
                for (Entry<String, String> entry : map.entrySet()) {  
                    //添加参数
                    params.add( new BasicNameValuePair(entry.getKey(),entry.getValue()) );  
                }         
            }
            
            //4、设置参数到请求对象中  
            try {
                response.setEntity(new UrlEncodedFormEntity(params, "utf-8"));
            } catch (UnsupportedEncodingException e1) {
                e1.printStackTrace();
            }  //5、设置header信息  
            response.setHeader("Content-type", "application/x-www-form-urlencoded");  
            response.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");  
            //添加cookie到头文件
            response.addHeader("Cookie", cookie);
            
            //6、设置编码
            //response.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));      
            //7、执行post请求操作,并拿到结果(同步阻塞)  
            CloseableHttpResponse httpResponse;
            try {
                httpResponse = (CloseableHttpResponse) httpClient.execute(response);      
                //获取结果实体  
                HttpEntity entity = httpResponse.getEntity();  
                if (entity != null) {  
                    //按指定编码转换结果实体为String类型                
                    body = EntityUtils.toString(entity, "utf-8");
                }
                EntityUtils.consume(entity);
            //释放链接  
            httpResponse.close();          
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }  
            return body;  
        }

     2、post请求获取头文件header信息

    //7执行post请求
    HttpResponse response = httpClient.execute(httpPost); //取头信息 Header[] headers = response.getAllHeaders(); for(int i=0;i<headers.length;i++) { System.out.println(headers[i].getName() +"=="+ headers[i].getValue()); }

    3、addHeader与setHeader区别

    HttpClient在添加头文件的时候,需要用到addHeader或setHeader

    区别:

    1、同名Header可以有多个 ,Header[] getHeaders(String name)。
    2、运行时使用的是第一个, Header getFirstHeader(String name)。
    3、addHeader,如果同名header已存在,则追加至原同名header后面
    4、setHeader,如果同名header已存在,则覆盖一个同名header

    2、源代码

    链接:http://files.cnblogs.com/files/airsen/HttpClientUtil.rar

    参考

    1、httpclient中文翻译:http://blog.csdn.net/column/details/httpclient.html

    2、httpclient翻译:http://blog.csdn.net/linghu_java/article/details/43306613

    3、轻松把玩HttpClient之模拟post请求示例:http://blog.csdn.net/xiaoxian8023/article/details/49863967

     4、http://www.codeweblog.com/httpclient-%E6%93%8D%E4%BD%9C%E5%B7%A5%E5%85%B7%E7%B1%BB/

  • 相关阅读:
    leetcode 11. 盛最多水的容器
    gluoncv 导入方式
    python import
    leetcode 55.跳跃游戏
    leetcode 31. 下一个排列
    gluoncv 下载预训练模型速度太慢
    gluoncv voc_detection
    shuf 按行打乱文本命令
    __call__
    @property 装饰器
  • 原文地址:https://www.cnblogs.com/airsen/p/6129462.html
Copyright © 2020-2023  润新知