HttpClient用法

1.一般步骤:

复制代码
1.创建链接:
    DefaultHttpClient httpClient = new DefaultHttpClient();
2.创建请求:
    HttpPost post = new HttpPost(URL);
3.设置参数:
    post.setEntity(new StringEntity(paramList));
4.设置头部:
    post.setHeader("X-Auth0-Token",token))  //自己规定的一些参数
    post.setHeader("Content-Type","application/json;charset=utf-8")  //json格式
5.执行请求、并接收返回:
    HttpResponse res = new httpClient.execute(post);
6.获取返回的信息体:
    String responseContent = EntityUtils.toString(res.getEntity(),"UTF-8");
7.解析返回的JSON:
    JSONObject json = JSON.parseObject(responseContent);
**8.判断是否请求成功:**
    if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){}
复制代码

注意:出现错误“HttpClient请求返回403”

//User-Agent会告诉网站服务器,访问者是通过什么工具来请求的,如果是爬虫请求,一般会拒绝,如果是用户浏览器,就会应答。所以添加一个请求信息告诉网站服务器自己是用户浏览器就可以啦。
httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.87 Safari/537.36");

2.参数问题:

复制代码
1.参数为Map<>的:
{
    "mobile":"1238293223"
}

                    HttpPost post_userId = new HttpPost(UserIdURL);

                    //获取userId
                    Gson gson = new Gson();
                    post_userId.setEntity(new StringEntity(gson.toJson(map)));
                    HttpResponse res = httpClient.execute(post_userId);
                    if(res != null){
                        String responseContent = EntityUtils.toString(res.getEntity());
                        JSONObject json = JSONObject.parseObject(responseContent);
                        userid = json.getString("userid");
                    }


2.参数为JSONArray:

                JSONArray array = JSONArray.parseArray(JSON.toJSONString(paramList));
                post.setEntity(new StringEntity(array.toString(), ContentType.APPLICATION_JSON));


3.参数为&name类型:
//设置参数  Map<String,String> map
            List<NameValuePair> list = new ArrayList<NameValuePair>();
            Iterator iterator = map.entrySet().iterator();
            while(iterator.hasNext()){
                Entry<String,String> elem = (Entry<String, String>) iterator.next();
                list.add(new BasicNameValuePair(elem.getKey(),elem.getValue()));
            }
            if(list.size() > 0){
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,charset); //转为&
                httpPost.setEntity(entity);
            }


4.参数为list<map<>>//List<Map<String,Object>> paramList,转为JSONArry
          HttpResponse res = null;
                JSONArray array = JSONArray.parseArray(JSON.toJSONString(paramList));
                post.setEntity(new StringEntity(array.toString(), StandardCharsets.UTF_8));
复制代码

3.get请求:

复制代码
DefaultHttpClient httpClient = new DefaultHttpClient();
/* ***** 1. 请求 */
HttpGet get = new HttpGet(apiURL+"?"+appId+"&"+appSecret);
/* ****** 2. 请求结束,返回结果 */
HttpResponse res = httpClient.execute(get);
/* 服务器成功地返回响应 */
HttpEntity httpEntity = res.getEntity();
String responseContent = EntityUtils.toString(httpEntity, "UTF-8");
 /* 将响应内容转化为json对象 */
JSONObject json = JSONObject.parseObject(responseContent);
复制代码

4.post请求:

复制代码
DefaultHttpClient httpClient = new DefaultHttpClient();
/* ***** 1. 请求 */
HttpPost post = new HttpPost(apiURL_create);
/* ****** 2. 请求结束,返回结果 */
HttpResponse res = null;
JSONArray array = JSONArray.parseArray(JSON.toJSONString(paramList));
post.setEntity(new StringEntity(array.toString(), StandardCharsets.UTF_8));
//设置头部参数
post.setHeader("Content-Type","application/json;charset=utf-8");
post.setHeader("X-Auth0-Token",getTokenByApptype(appType));
res = httpClient.execute(post);
/* 服务器是否成功地返回响应 */
if(res != null){
/* 解析响应,判断状态码 */
  if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
       String responseContent = EntityUtils.toString(res.getEntity(),"UTF-8");
//     logger.info("success ----->  "+responseContent);
       /* 将响应内容转化为json对象 */
       JSONObject json = JSONObject.parseObject(responseContent);
       JSONObject data = json.getJSONObject("data");
       //若传入的参数有误
       if(data == null){
           taskId_list.add(json.getString("msg"));
           taskId_list.add(json.getString("code"));
           return taskId_list;
        }
       JSONArray jsonArray = data.getJSONArray("taskIds");
       taskId_list = JSONObject.parseArray(jsonArray.toJSONString(),String.class);
       //一个失败,所有的都失败
       if(taskId_list.size() < paramList.size()){
            taskId_list.clear();
            taskId_list.add("全部创建失败!");
        }
       return taskId_list; //"执行成功"
  }
}
复制代码

5.代码样例:

复制代码
package com.kingdee.eas.custom.cfinv.utils;

import com.kingdee.bos.ui.face.CoreUIObject;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.List;
import javax.net.ssl.SSLContext;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.HttpResponseException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.json.JSONException;
import org.json.JSONObject;

public class HttpUtils {

      private static Logger logger = CoreUIObject.getLogger(HttpUtils.class);

      public static HttpClient getHttpClient()
      {
        CloseableHttpClient httpClient = HttpClients.custom()
          .setConnectionManager(ConnectionManager.manager).build();
        return httpClient;
      }

      public static JSONObject doPost(String url, String params, String charset) throws Exception
      {
        logger.error("HttpUtils:start-----doPost");
        HttpClient hc = getHttpClient();
        HttpPost httpPost = new HttpPost(url);

        BufferedReader bufferedReader = null;
        try {
          logger.error("获取到response之前");
          StringEntity se = new StringEntity(params, charset);
          se.setContentEncoding(new BasicHeader("Content-Type", "application/json"));
          httpPost.setEntity(se);

          HttpResponse response = hc.execute(httpPost);
          HttpEntity e = response.getEntity();
          StringBuffer buffer = new StringBuffer();
          logger.error("获取到response之后");
          if (e != null) {
            Long len = Long.valueOf(e.getContentLength());
            if ((len.longValue() != -1L) && (len.longValue() < 2048L)) {
                logger.error("2048L");
                logger.error("2048L"+buffer.toString());
              buffer.append(EntityUtils.toString(e, charset));
            } else {
                logger.error("追加"+buffer.toString());
              bufferedReader = new BufferedReader(
                new InputStreamReader(e.getContent(), charset));
              String str = null;
              while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
              }
            }
          }
            logger.error("报文:"+buffer.toString());
          if (response.getStatusLine().getStatusCode() >= 300) {
              logger.error("code大于300:"+buffer.toString());
            throw new HttpResponseException(
              response.getStatusLine().getStatusCode(), 
              response.getStatusLine().getReasonPhrase());
          }

          if (e == null) {
              logger.error("返回内容为空");
            throw new ClientProtocolException("返回内容为空");
          }

          logger.error("HttpUtils.doPost=\r\n"+response.getStatusLine().getStatusCode() + "\n" + 
            buffer.toString());
        
          JSONObject resultObject = new JSONObject(buffer.toString());
          logger.error("HttpUtils.resultObject=\r\n"+resultObject);
          return resultObject;
        }
        catch (Exception e) {
            logger.error("doPost错误:"+e.getMessage(), e);
            throw new Exception(e);
        }
        finally {
          if (bufferedReader != null) {
            try {
              bufferedReader.close();
            } catch (IOException e) {
              e.printStackTrace();
              logger.error("dopost错误:"+e,e);
              throw new RuntimeException(e);
            }
          }
          logger.error("dopost关闭");
//          httpPost.releaseConnection();
        }
      }

      public static byte[] downloadFile(String url) {
          logger.error("HttpUtils:start-----downloadFile");
        HttpClient hc = getHttpClient();
        HttpGet httpGet = new HttpGet(url);
        InputStream in = null;
        byte[] b = (byte[])null;
        try {
          HttpResponse response = hc.execute(httpGet);
          HttpEntity e = response.getEntity();
          if (response.getStatusLine().getStatusCode() >= 300) {
            throw new HttpResponseException(
              response.getStatusLine().getStatusCode(), 
              response.getStatusLine().getReasonPhrase());
          }
          if (e != null) {
            in = e.getContent();
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            int l = 0;
            byte[] tmp = new byte[1024];
            while ((l = in.read(tmp)) != -1) {
              out.write(tmp, 0, l);
            }
            b = out.toByteArray();
            out.close();
          } else {
            throw new ClientProtocolException("返回内容为空");
          }
          return b;
        }
      
        catch (Exception e) {
        }
        finally {
          if (in != null) {
            try {
              in.close();
            } catch (IOException e) {
              e.printStackTrace();
              logger.error("downloadFile错误:"+e,e);
              throw new RuntimeException(e);
            }
          }
//          httpGet.releaseConnection();
        }
        return null;
      }

      public static String encode(String[] args) {
        char[] hexDigits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
        if ((args == null) || (args.length == 0)) return "";
        StringBuffer sb = new StringBuffer();
        for (String str : args) {
          sb.append(str);
        }
        byte[] bytes = sb.toString().getBytes();
        try {
          MessageDigest mdInst = MessageDigest.getInstance("MD5");
          mdInst.update(bytes);
          byte[] md = mdInst.digest();
          char[] ciphertext = new char[2 * md.length];
          int k = 0;
          for (int j = 0; j < md.length; ++j) {
            byte b0 = md[j];
            ciphertext[(k++)] = hexDigits[(b0 >>> 4 & 0xF)];
            ciphertext[(k++)] = hexDigits[(b0 & 0xF)];
          }
          return new String(ciphertext);
        } catch (NoSuchAlgorithmException e) {
          e.printStackTrace();
          logger.error("encode错误:"+e,e);
          throw new RuntimeException(e);
        }
      }

      public static JSONObject doGet(String url, String charset)
      {
          logger.error("HttpUtils:start-----doGet");
        HttpClient hc = getHttpClient();
        HttpGet httpGet = new HttpGet(url);
        BufferedReader bufferedReader = null;
        try {
          HttpResponse response = hc.execute(httpGet);
          HttpEntity e = response.getEntity();
          StringBuffer buffer = new StringBuffer();
          if (e != null) {
            Long len = Long.valueOf(e.getContentLength());
            if ((len.longValue() != -1L) && (len.longValue() < 2048L)) {
              buffer.append(EntityUtils.toString(e, charset));
            } else {
              bufferedReader = new BufferedReader(
                new InputStreamReader(e.getContent(), 
                charset));
              String str = null;
              while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
              }
            }
          }
          if (response.getStatusLine().getStatusCode() >= 300) {
            throw new HttpResponseException(response.getStatusLine().getStatusCode(), 
              response.getStatusLine().getReasonPhrase());
          }
          if (e == null) {
            throw new ClientProtocolException("返回内容为空");
          }
          logger.error("doGet报文状态码"+response.getStatusLine().getStatusCode() + "\n" + buffer.toString());
          logger.info(response.getStatusLine().getStatusCode() + "\n" + buffer.toString());

          return new JSONObject(buffer.toString());
        }
        catch (UnsupportedEncodingException e1)
        {
            logger.error("doGet错误:"+e1,e1);
        }
        catch (ClientProtocolException e)
        {
            logger.error("doGet错误:"+e,e);
        }
        catch (IOException e)
        {
            logger.error("doGet错误:"+e,e);
        }
        catch (JSONException e) {
            logger.error("doGet错误:"+e,e);
        }
        finally {
          if (bufferedReader != null) {
            try {
              bufferedReader.close();
            } catch (IOException e) {
              e.printStackTrace();
              logger.error("doGet错误:"+e,e);
              throw new RuntimeException(e);
            }
          }
//          httpGet.releaseConnection();
        }
        return null;
      }

      public static JSONObject doPost(String url, List<NameValuePair> params, String charset)
      {
        HttpClient hc = getHttpClient();
        HttpPost httpPost = new HttpPost(url);

        BufferedReader bufferedReader = null;
        try {
          StringEntity se = new UrlEncodedFormEntity(params, "UTF-8");
          se.setContentEncoding(new BasicHeader("Content-Type", "application/x-www-form-urlencoded"));
          httpPost.setEntity(se);

          HttpResponse response = hc.execute(httpPost);
          HttpEntity e = response.getEntity();
          StringBuffer buffer = new StringBuffer();
          if (e != null) {
            Long len = Long.valueOf(e.getContentLength());
            if ((len.longValue() != -1L) && (len.longValue() < 2048L)) {
              buffer.append(EntityUtils.toString(e, charset));
            } else {
              bufferedReader = new BufferedReader(
                new InputStreamReader(e.getContent(), charset));
              String str = null;
              while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
              }
            }
          }
          if (response.getStatusLine().getStatusCode() >= 300) {
            throw new HttpResponseException(
              response.getStatusLine().getStatusCode(), 
              response.getStatusLine().getReasonPhrase());
          }

          if (e == null) {
            throw new ClientProtocolException("返回内容为空");
          }

          logger.info(response.getStatusLine().getStatusCode() + "\n" + 
            buffer.toString());
          return new JSONObject(buffer.toString());
        } catch (Exception e) {
        }
        finally {
          if (bufferedReader != null) {
            try {
              bufferedReader.close();
            } catch (IOException e) {
              e.printStackTrace();
              throw new RuntimeException(e);
            }
          }
//          httpPost.releaseConnection();
        }
        return null;
      }

      public static String doGet4String(String url, String charset)
      {
        HttpClient hc = getHttpClient();
        HttpGet httpGet = new HttpGet(url);
        BufferedReader bufferedReader = null;
        try {
          HttpResponse response = hc.execute(httpGet);
          HttpEntity e = response.getEntity();
          StringBuffer buffer = new StringBuffer();
          if (e != null) {
            Long len = Long.valueOf(e.getContentLength());
            if ((len.longValue() != -1L) && (len.longValue() < 2048L)) {
              buffer.append(EntityUtils.toString(e, charset));
            } else {
              bufferedReader = new BufferedReader(
                new InputStreamReader(e.getContent(), 
                charset));
              String str = null;
              while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
              }
            }
          }
          if (response.getStatusLine().getStatusCode() >= 300) {
            throw new HttpResponseException(response.getStatusLine().getStatusCode(), 
              response.getStatusLine().getReasonPhrase());
          }
          if (e == null) {
            throw new ClientProtocolException("返回内容为空");
          }
          logger.info(response.getStatusLine().getStatusCode() + "\n" + buffer.toString());

          return buffer.toString();
        } catch (Exception e) {
        }
        finally {
          if (bufferedReader != null) {
            try {
              bufferedReader.close();
            } catch (IOException e) {
              e.printStackTrace();
              throw new RuntimeException(e);
            }
          }
//          httpGet.releaseConnection();
        }
        return null;
      }

      public static JSONObject doPost(String url, HttpEntity entity, String charset)
      {
        HttpClient hc = getHttpClient();
        HttpPost httpPost = new HttpPost(url);

        BufferedReader bufferedReader = null;
        try {
          httpPost.setEntity(entity);

          HttpResponse response = hc.execute(httpPost);
          HttpEntity e = response.getEntity();
          StringBuffer buffer = new StringBuffer();
          if (e != null) {
            Long len = Long.valueOf(e.getContentLength());
            if ((len.longValue() != -1L) && (len.longValue() < 2048L)) {
              buffer.append(EntityUtils.toString(e, charset));
            } else {
              bufferedReader = new BufferedReader(
                new InputStreamReader(e.getContent(), charset));
              String str = null;
              while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
              }
            }
          }
          if (response.getStatusLine().getStatusCode() >= 300) {
            throw new HttpResponseException(
              response.getStatusLine().getStatusCode(), 
              response.getStatusLine().getReasonPhrase());
          }

          if (e == null) {
            throw new ClientProtocolException("返回内容为空");
          }

          logger.info(response.getStatusLine().getStatusCode() + "\n" + 
            buffer.toString());
          return new JSONObject(buffer.toString());
        } catch (Exception e) {
        }
        finally {
          if (bufferedReader != null) {
            try {
              bufferedReader.close();
            } catch (IOException e) {
              e.printStackTrace();
              throw new RuntimeException(e);
            }
          }
//          httpPost.releaseConnection();
        }
        return null;
      }

      private static class ConnectionManager
      {
        private static PoolingHttpClientConnectionManager manager = null;

        static {
          SSLContext sslContext = null;
          try {
            sslContext = SSLContexts.custom().loadTrustMaterial(
              null, new TrustStrategy()
            {
              public boolean isTrusted(X509Certificate[] arg0, String arg1)
                throws CertificateException
              {
                return true;
              }
            }).build();
          } catch (KeyManagementException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
          } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
          } catch (KeyStoreException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
          }
          SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
            sslContext, 
            new String[] { "TLSv1" }, 
            null, 
            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
          Registry registry = RegistryBuilder.create().register(
            "http", PlainConnectionSocketFactory.INSTANCE)
            .register("https", sslsf).build();
          manager = new PoolingHttpClientConnectionManager(registry);
          manager.setDefaultMaxPerRoute(20);
        }
      }

}
 
复制代码

 

posted @   湘summer  阅读(312)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
点击右上角即可分享
微信分享提示