httpclient整理

package com.yjl.util;

import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.annotation.NotThreadSafe;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
 * Created by Administrator on 2018/4/27.
 */
public class HttpClientUtil {

  final static String authorValue =
          "eyJhbGciOiJSUzI1NiIsImtpZCI6IjRDNTQwNzlDQTU4OUZDRUREMTg5NzYzRUZBQTU4MTUzNTQ5MUNCOEMiLCJ0eXAiOiJKV1QiLCJ4NXQiOiJURlFIbktXSl9PM1JpWFktLXFXQlUxU1J5NHcifQ.eyJuYmYiOjE1NTQyNjAxODIsImV4cCI6MTU1NDQzMjk4MiwiaXNzIjoiaHR0cDovL29hdXRoOjQwMDAiLCJhdWQiOlsiaHR0cDovL29hdXRoOjQwMDAvcmVzb3VyY2VzIiwib3BlbmFwaSJdLCJjbGllbnRfaWQiOiJhcHAuc2RrLnJlZnJlc2giLCJzdWIiOiItMSIsImF1dGhfdGltZSI6MTU1NDI2MDE4MiwiaWRwIjoibG9jYWwiLCJlY29kZSI6IkUwMDE4OTgwIiwibG9naW5fbmFtZSI6IkUwMDE4OTgwIiwiaWRlbnRpZmljYXRpb24iOiIiLCJzY29wZSI6WyJvcGVuYXBpIiwib2ZmbGluZV9hY2Nlc3MiXSwiYW1yIjpbImVudGVycHJpc2VfYXBwIl19.fuEnQiB2xgMX5CG1UFY_9bUxjpzx8eKHHlb6fIc1_JgPDn45DhLNU1gNO_oLE4_jkThpR0WeotxYGgU3iv-9myOZWlWGfH1ClOfL7JR8jEATp0VYTWNpA8SQ5wDmbq-MnKcqVIxsFUXH1EVrW0pd_lc6eRHfTHkgJPrutBEstVoeFCOuNo2iCBtswV9yaZroJTBq-FPgEBHphS4Q4TotcO_vE3oD6qFrXs2w9-Ln3C0bLftxnEFcsO_iKIYb3K6VOSZACKPW7djI5w_U7Oj-2jR0ULGpF43J983NksenTMP4LW4oU4KjNy0RxHbNsbvT-Y8lN3oE0SwnAOeAPk5QCkfhAXaHOwLXNCiqYxABG0sWWHztuJkkxgcCVmVDwCSuIWhL5DFVJCN-IEirFXhvhLznV9ym9wxvz0xE84uVVEtx4KL8-z0E0Fcf3vYAGLuC8_QD3oyG1V81x0G7rNPrK-UomAYkRH1ZCn0KhLR3KzqzGbNUcGlpJrnJze1KJd6ZNY0Z3J_4zK3UaMf5TdryU18pfKB8ZOo3I7tM4eer6MNPNBvSu-gA_DGNDyXmpSNgtoCLAprc9UHjgiALybJGbeQCj_z2nEkXX9Aw9EpwguOVdQvLjvyD_ul_yOK3VPiZmKQHOy9jwz8GyqW2iO1UNIMbrRc3_RZ_DrR-R6CHPK0";
  public static String doGet(String url, Map<String, String> param) {

    // 创建Httpclient对象
    CloseableHttpClient httpclient = HttpClients.createDefault();

    String resultString = "";
    CloseableHttpResponse response = null;
    try {
      // 创建uri
      URIBuilder builder = new URIBuilder(url);
      if (param != null) {
        for (String key : param.keySet()) {
          builder.addParameter(key, param.get(key));
        }
      }
      URI uri = builder.build();

      // 创建http GET请求
      HttpGet httpGet = new HttpGet(uri);

      // 执行请求
      response = httpclient.execute(httpGet);
      // 判断返回状态是否为200
      if (response.getStatusLine().getStatusCode() == 200) {
        resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        if (response != null) {
          response.close();
        }
        httpclient.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    return resultString;
  }

  /**
   * get 请求
   * @param url
   * @param authorValue
   * @param para
   * @return
   */
  public static JSONObject doGetJson(String url, String authorValue, Map<String, String> para){
    JSONObject response = null;
    try{
      HttpClient client = new DefaultHttpClient();

      URIBuilder builder = new URIBuilder(url);
      Set<String> set = para.keySet();
      for(String key: set){
        builder.setParameter(key, para.get(key));
      }
      HttpGet request = new HttpGet(builder.build());
      if(StringUtils.isNotEmpty(authorValue)){
        request.setHeader("Authorization",authorValue);
      }
      request.setHeader("ContentTye","application/json");
      RequestConfig requestConfig = RequestConfig.custom()
              .setSocketTimeout(6000)
              .setConnectTimeout(6000)
              .setConnectionRequestTimeout(6000).build();
      request.setConfig(requestConfig);


      HttpResponse res = client.execute(request);
//      if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
      HttpEntity entity = res.getEntity();
      String result = EntityUtils.toString(res.getEntity());// 返回json格式:
      response = JSONObject.fromObject(result);
//      }
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
    return response;
  }

  public static String doGet(String url) {
    return doGet(url, null);
  }

  public static String doPost(String url, Map<String, String> param) {
    // 创建Httpclient对象
    CloseableHttpClient httpClient = HttpClients.createDefault();
    CloseableHttpResponse response = null;
    String resultString = "";
    try {
      // 创建Http Post请求
      HttpPost httpPost = new HttpPost(url);
      // 创建参数列表
      if (param != null) {
        List<NameValuePair> paramList = new ArrayList<>();
        for (String key : param.keySet()) {
          paramList.add(new BasicNameValuePair(key, param.get(key)));
        }
        // 模拟表单
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList,"utf-8");
        httpPost.setEntity(entity);
      }
      // 执行http请求
      response = httpClient.execute(httpPost);
      resultString = EntityUtils.toString(response.getEntity(), "utf-8");
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        response.close();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }

    return resultString;
  }

  public static String doPostJson(String url, String json) {
    // 创建Httpclient对象
    CloseableHttpClient httpClient = HttpClients.createDefault();
    CloseableHttpResponse response = null;
    String resultString = "";
    try {
      // 创建Http Post请求
      HttpPost httpPost = new HttpPost(url);
      // 创建请求内容
      httpPost.setHeader("Content-Type","application/json");
      StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
      httpPost.setEntity(entity);
      // 执行http请求
      response = httpClient.execute(httpPost);
      resultString = EntityUtils.toString(response.getEntity(), "utf-8");
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        response.close();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }

    return resultString;
  }

  public static String doPostJsonToAnLian(String url, String json) {
    // 创建Httpclient对象
    CloseableHttpClient httpClient = HttpClients.createDefault();
    CloseableHttpResponse response = null;
    String resultString = "";
    try {
      // 创建Http Post请求
      HttpPost httpPost = new HttpPost(url);
      String token = "Bearer "+authorValue;
      if(StringUtils.isNotEmpty(authorValue)){
        httpPost.addHeader("Authorization",token);
      }
      httpPost.addHeader("Content-Type","application/json");
      // 创建请求内容
      StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
      httpPost.setEntity(entity);
      // 执行http请求
      response = httpClient.execute(httpPost);
      resultString = EntityUtils.toString(response.getEntity(), "utf-8");
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        response.close();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
    return resultString;
  }

  public static String doPutJsonToAnLian(String url, String json) {
    // 创建Httpclient对象
    CloseableHttpClient httpClient = HttpClients.createDefault();
    CloseableHttpResponse response = null;
    String resultString = "";
    try {
      // 创建Http Put请求
      HttpPut httpPut = new HttpPut(url);
      String token = "Bearer "+authorValue;
      if(StringUtils.isNotEmpty(authorValue)){
        httpPut.addHeader("Authorization",token);
      }
      httpPut.addHeader("Content-Type","application/json");
      // 创建请求内容
      StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
      httpPut.setEntity(entity);
      // 执行http请求
      response = httpClient.execute(httpPut);
      resultString = EntityUtils.toString(response.getEntity(), "utf-8");
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        response.close();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
    return resultString;
  }

  public static String doDeleteJsonToAnLian(String url, String json) {
    // 创建Httpclient对象
    CloseableHttpClient httpClient = HttpClients.createDefault();
    CloseableHttpResponse response = null;
    String resultString = "";
    try {
      // 创建Http Delete请求
      HttpDeleteWithBody httpDelete = new HttpDeleteWithBody(url);
      String token = "Bearer "+authorValue;
      if(StringUtils.isNotEmpty(authorValue)){
        httpDelete.addHeader("Authorization",token);
      }
      httpDelete.addHeader("Content-Type","application/json");
      // 创建请求内容
      StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
      httpDelete.setEntity(entity);
      // 执行http请求
      response = httpClient.execute(httpDelete);
      resultString = EntityUtils.toString(response.getEntity(), "utf-8");
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        response.close();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
    return resultString;
  }
}

/**
 * 内部类,删除调用+传参
 */
@NotThreadSafe
class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase {
  public static final String METHOD_NAME = "DELETE";

  @Override
  public String getMethod() { return METHOD_NAME; }

  public HttpDeleteWithBody(final String uri) {
    super();
    setURI(URI.create(uri));
  }
  public HttpDeleteWithBody(final URI uri) {
    super();
    setURI(uri);
  }
  public HttpDeleteWithBody() { super(); }
}

 

posted @ 2019-04-04 17:20  kerala  阅读(290)  评论(0编辑  收藏  举报