java http请求

使用前需要引入架包

通过mvn引入

代码片.

<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<!-- <version>4.5.6</version> -->
		</dependency>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpcore</artifactId>
			<!-- <version>4.4.10</version> -->
		</dependency>

具体代码如下:

package com.common.util;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

/**
 * @describe http请求工具类
 */
public class HttpClientUtil {

  private static final Logger LOG = Logger.getLogger(HttpClientUtil.class);

  /**
   * 发送json数据获取结果
   * @param json
   * @return
   */
  public static JSONObject doPost(JSONObject json,String url){
    JSONObject response = null;
    String uuid = UUID.randomUUID().toString();
    LOG.info(uuid + "请求入参-->"+json.toString());
    try {
      //创建默认的httpClient实例
      HttpPost post = new HttpPost(url);
      CloseableHttpClient client = getHttpClient();
      StringEntity s = new StringEntity(json.toString(),"UTF-8");
      s.setContentType("application/json");//发送json数据需要设置contentType
      post.addHeader("Content-type","application/json; charset=utf-8");
      post.setHeader("Accept", "application/json");
      post.setEntity(s);
      HttpResponse res = client.execute(post);
      if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
        HttpEntity entity = res.getEntity();
        String result = EntityUtils.toString(entity,"UTF-8");// 返回json格式:
        LOG.info(uuid + "响应内容-->" + result);
        response = JSONObject.fromObject(result);
      } else {
          LOG.info(uuid + "响应状态-->"+ res.getStatusLine());
      }
    } catch (Exception e) {
      LOG.info(uuid + "响应失败-->" , e);
    }
    return response;
  }

  /**
   * 发送json数据获取结果
   * @param json
   * @return
   */
  public static JSONObject doRequestDataPost(JSONObject json,String url){
    //创建默认的httpClient实例
    String uuid = UUID.randomUUID().toString();
    LOG.info(uuid + "------------------------------------------split line------------------------------------------------------");
    LOG.info("请求地址-->"+url);
    HttpPost post = new HttpPost(url);
    CloseableHttpClient client = getHttpClient();
    JSONObject response = null;
    UrlEncodedFormEntity encodedFormEntity = null;
    try {
      post.addHeader("Content-type", "application/x-www-form-urlencoded;charset=utf-8");
      post.addHeader("Accept","application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
      ArrayList<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>();
      pairs.add(new BasicNameValuePair("requestData", json.toString()));
      if(pairs != null) {
        encodedFormEntity = new UrlEncodedFormEntity(pairs, "utf-8");
        post.setEntity(encodedFormEntity);
      }
      HttpResponse res = client.execute(post);
      LOG.info(uuid + "请求入参-->"+json.toString());
      LOG.info(uuid + "响应状态-->"+ res.getStatusLine());
      if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
        HttpEntity entity = res.getEntity();
        String result = EntityUtils.toString(entity,"UTF-8");// 返回json格式:
        LOG.info(uuid + "响应内容-->" + result);
        response = JSONObject.fromObject(result);
      }
    } catch (Exception e) {
      LOG.info(uuid + "doRequestDataPost异常",e);
    }
    LOG.info(uuid + "------------------------------------------split line------------------------------------------------------");
    return response;
  }

  /**
   * HTTP Get 获取内容
   * @param url 请求的url地址 ?之前的地址
   * @param params 请求的参数
   * @param charset 编码格式
   * @return 页面内容
   */
  public static String sendGet(String url, Map<String, Object> params, String charset) {
    String uuid = UUID.randomUUID().toString();
    String result = null;
    LOG.info(uuid + "------------------------------------------split line------------------------------------------------------");
    try {
      if(params !=null && !params.isEmpty()){
        List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size());
        for (String key :params.keySet()){
          pairs.add(new BasicNameValuePair(key, params.get(key).toString()));
        }
        url +="?"+ EntityUtils.toString(new UrlEncodedFormEntity(pairs), charset);
      }
      HttpGet httpGet = new HttpGet(url);
      CloseableHttpClient client = getHttpClient();
      CloseableHttpResponse response = client.execute(httpGet);
      LOG.info(uuid + "请求地址-->"+url);
      LOG.info(uuid + "响应状态-->"+ response.getStatusLine());
      int statusCode = response.getStatusLine().getStatusCode();
      if(statusCode !=200){
        httpGet.abort();
        throw new RuntimeException("HttpClient,error status code :" + statusCode);
      }
      HttpEntity entity = response.getEntity();
      if (entity != null) {
        result = EntityUtils.toString(entity, charset);
        LOG.info(uuid + "响应内容-->" + result);
        EntityUtils.consume(entity);
        response.close();
      }
    }catch (Exception e){
      LOG.info(uuid + "响应失败-->" , e);
    }
    LOG.info(uuid + "------------------------------------------split line------------------------------------------------------");
    return result;
  }

  /**
   * 获取httpClient链接
   * @return
   */
  private static CloseableHttpClient getHttpClient(){
    return HttpClients.createDefault();
  }

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值