• 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 -->
  • 相关阅读:
    电脑开机小键盘灯不亮,应该怎么设置?
    关于SqlServer数据库日期函数
    SqlServer数据库几种字段类型对比
    如何查找计算机端口?
    实用的几个小命令
    SqlServer中创建Oracle连接服务器
    局域网内设置打印机
    SqlServer2008数据库自动备份设置
    文件内容替换BAT
    Dockerfile文件与常用指令详解(2) Marathon
  • 原文地址:https://www.cnblogs.com/applemoon/p/6399653.html
Copyright © 2020-2023  润新知