zoukankan      html  css  js  c++  java
  • httpclient 4.0 使用

    httclient 正常流程

    1、创建httpclient实例

    HttpClient httpClient = new DefaultHttpClient();
    CloseableHttpClient httpclient =  HttpClients.createDefault();

    2、创建请求实例

    HttpGet httpGet = new HttpGet(url);
    HttpPost httpPost = new HttpPost(url);

    3、补充头信息(可选)

    httpPost.addHeader("Referer", "http://iservice.10010.com/e4/query/basic/history_list.html");
    httpPost.addHeader(" Cookie ", " td_cookie=18446744072103645798; mallcity=31|310; ");

    4、补充请求实体

    1)url是restful风格,已经包含需要传入的参数。可以跳过直接到下一步操作。

    url="https://ssoqa.99bill.com/sso/login/smsvalidate.htm?method=loginErrorCount&idContent=1234567" 

    2)表单

    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair("querytype", "0001"));
    nvps.add(new BasicNameValuePair("querycode", "0001"));
    nvps.add(new BasicNameValuePair("billdate", "201608"));
    nvps.add(new BasicNameValuePair("flag", "2"));
    httpPost.setEntity(new UrlEncodedFormEntity(nvps));

    5、请求执行

    HttpResponse response = httpClient.execute(httpGet);
    CloseableHttpResponse response = httpclient.execute(httpGet);
    byte[] response = httpClient.execute(httpGet,handler);

    6、读取响应内容

    if (response.getStatusLine().getStatusCode() == 200) {
        HttpEntity entity = response.getEntity();
         if (entity != null) {
                         InputStream instream = entity.getContent();
                try {
               // do something useful
                 } finally {
                    instream.close();
                }
            }
       } 

    7、释放连接

    response.close(); 

    需要引用的jar

            <!-- httpclient -->
            <dependency>
                <groupId>org.apache.httpcomponents</groupId>
                <artifactId>httpclient</artifactId>
                <version>4.3.4</version>
            </dependency>
            <!-- httpclient -->
  • 相关阅读:
    【笔记】vue中websocket心跳机制
    【笔记】MySQL删除重复记录保留一条
    oss上传实例
    jquery实现图片点击旋转
    IDEA卡顿解决方法
    斐波那契数列
    【笔记】接口发送数据及接收
    【笔记】获取新浪财经最新的USDT-CNY的汇率
    【笔记】Java 信任所有SSL证书(解决PKIX path building failed问题)
    IDEA中报错“cannot resolve symbol toDF”,但编译正确可以运行
  • 原文地址:https://www.cnblogs.com/applemoon/p/6399653.html
Copyright © 2011-2022 走看看