Java http请求封装工具类代码实例

java实现http请求的方法常用有两种,一种则是通过java自带的标准类HttpURLConnection去实现,另一种是通过apache的httpclient去实现。

本文用httpclient去实现,需要导入httpclient和httpcore两个jar包,测试时用的httpclient-4.5.1和httpcore-4.4.3。

HttpMethod.java

package demo;
public enum HttpMethod {
  GET, POST;
}

HttpHeader.java

package demo;

import java.util.HashMap;
import java.util.Map;

/**
 * 请求头
 */
public class HttpHeader {
  private Map<String, String> params = new HashMap<String, String>();

  public HttpHeader addParam(String name, String value) {
    this.params.put(name, value);
    return this;
  }

  public Map<String, String> getParams() {
    return this.params;
  }
}

HttpParamers.java

package demo;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import com.alibaba.fastjson.JSON;

/**
 * 请求参数
 */
public class HttpParamers {
  private Map<String, String> params = new HashMap<String, String>();
  private HttpMethod httpMethod;
  private String jsonParamer = "";

  public HttpParamers(HttpMethod httpMethod) {
    this.httpMethod = httpMethod;
  }

  public static HttpParamers httpPostParamers() {
    return new HttpParamers(HttpMethod.POST);
  }

  public static HttpParamers httpGetParamers() {
    return new HttpParamers(HttpMethod.GET);
  }

  public HttpParamers addParam(String name, String value) {
    this.params.put(name, value);
    return this;
  }

  public HttpMethod getHttpMethod() {
    return this.httpMethod;
  }

  public String getQueryString(String charset) throws IOException {
    if ((this.params == null) || (this.params.isEmpty())) {
      return null;
    }
    StringBuilder query = new StringBuilder();
    Set<Map.Entry<String, String>> entries = this.params.entrySet();

    for (Map.Entry<String, String> entry : entries) {
      String name = entry.getKey();
      String value = entry.getValue();
      query.append("&").append(name).append("=").append(URLEncoder.encode(value, charset));
    }
    return query.substring(1);
  }

  public boolean isJson() {
    return !isEmpty(this.jsonParamer);
  }

  public Map<String, String> getParams() {
    return this.params;
  }

  public String toString() {
    return "HttpParamers " + JSON.toJSONString(this);
  }

  public String getJsonParamer() {
    return this.jsonParamer;
  }

  public void setJsonParamer() {
    this.jsonParamer = JSON.toJSONString(this.params);
  }

  private static boolean isEmpty(CharSequence cs) {
    return (cs == null) || (cs.length() == 0);
  }
}

HttpClient.java

package demo;

import java.io.IOException;
import java.util.Map;
import java.util.Set;

import org.apache.http.HttpEntity;
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.client.methods.HttpRequestBase;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

public class HttpClient {
  public static final String DEFAULT_CHARSET = "UTF-8";
  public static final String JSON_CONTENT_FORM = "application/json;charset=UTF-8";
  public static final String CONTENT_FORM = "application/x-www-form-urlencoded;charset=UTF-8";

  public static String doService(String url, HttpParamers paramers, HttpHeader header, int connectTimeout, int readTimeout) throws Exception {
    HttpMethod httpMethod = paramers.getHttpMethod();
    switch (httpMethod) {
      case GET:
        return doGet(url, paramers, header, connectTimeout, readTimeout);
      case POST:
        return doPost(url, paramers, header, connectTimeout, readTimeout);
    }
    return null;
  }

  /**
   * post方法
   * @param url
   * @param paramers
   * @param header
   * @param connectTimeout
   * @param readTimeout
   * @return
   * @throws IOException
   */
  public static String doPost(String url, HttpParamers paramers, HttpHeader header, int connectTimeout, int readTimeout) throws IOException {
    String responseData = "";
    CloseableHttpClient httpClient = null;
    CloseableHttpResponse httpResponse = null;
    try{
      String query = null;
      HttpPost httpPost = new HttpPost(url);
      setHeader(httpPost, header);
      if (paramers.isJson()) {
        //json数据
        httpPost.setHeader(HTTP.CONTENT_TYPE, JSON_CONTENT_FORM);
        query = paramers.getJsonParamer();
      } else {
        //表单数据
        httpPost.setHeader(HTTP.CONTENT_TYPE, CONTENT_FORM);
        query = paramers.getQueryString(DEFAULT_CHARSET);
      }
      if(query != null){
        HttpEntity reqEntity = new StringEntity(query);
        httpPost.setEntity(reqEntity);
      }
      httpClient = HttpClients.createDefault();
      httpResponse = httpClient.execute(httpPost);
      HttpEntity resEntity = httpResponse.getEntity();
      responseData = EntityUtils.toString(resEntity);
    } catch (Exception e){
      e.printStackTrace();
    } finally{
      httpResponse.close();
      httpClient.close();
    }
    return responseData;
  }

  /**
   * get方法
   * @param url
   * @param params
   * @param header
   * @param connectTimeout
   * @param readTimeout
   * @return
   * @throws IOException
   */
  public static String doGet(String url, HttpParamers params, HttpHeader header, int connectTimeout, int readTimeout) throws IOException {
    String responseData = "";
    CloseableHttpClient httpClient = null;
    CloseableHttpResponse httpResponse = null;
    try{
      String query = params.getQueryString(DEFAULT_CHARSET);
      url = buildGetUrl(url, query);
      HttpGet httpGet = new HttpGet(url);
      setHeader(httpGet, header);
      httpClient = HttpClients.createDefault();
      httpResponse = httpClient.execute(httpGet);
      HttpEntity resEntity = httpResponse.getEntity();
      responseData = EntityUtils.toString(resEntity);
    } catch (Exception e){
      e.printStackTrace();
    } finally{
      httpResponse.close();
      httpClient.close();
    }
    return responseData;
  }

  private static void setHeader(HttpRequestBase httpRequestBase, HttpHeader header){
    if(header != null){
      Map<String,String> headerMap = header.getParams();
      if (headerMap != null && !headerMap.isEmpty()) {
        Set<Map.Entry<String, String>> entries = headerMap.entrySet();
        for (Map.Entry<String, String> entry : entries) {
          String name = entry.getKey();
          String value = entry.getValue();
          httpRequestBase.setHeader(name, value);
        }
      }
    }
  }

  private static String buildGetUrl(String url, String query) throws IOException {
    if (query == null || query.equals("")) {
      return url;
    }
    StringBuilder newUrl = new StringBuilder(url);
    boolean hasQuery = url.contains("?");
    boolean hasPrepend = (url.endsWith("?")) || (url.endsWith("&"));
    if (!hasPrepend) {
      if (hasQuery) {
        newUrl.append("&");
      } else {
        newUrl.append("?");
        hasQuery = true;
      }
    }
    newUrl.append(query);
    hasPrepend = false;
    return newUrl.toString();
  }
}

HttpService.java

package demo;

import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;

public class HttpService {
  private String serverUrl;
  private int connectTimeout = 15000;
  private int readTimeout = 30000;
  public HttpService(String serverUrl) {
    this.serverUrl = serverUrl.trim();
  }
  public Map<String, Object> commonService(String serviceUrl, HttpParamers paramers) throws Exception{
    return commonService(serviceUrl, paramers, null);
  }
  public Map<String, Object> commonService(String serviceUrl, HttpParamers paramers, HttpHeader header) throws Exception{
    String response = service(serviceUrl, paramers, header);
    try {
      Map<String, Object> result = JSONObject.parseObject(response, new TypeReference<Map<String, Object>>() {});
      if ((result == null) || (result.isEmpty())) {
        throw new Exception("远程服务返回的数据无法解析");
      }
      Integer code = (Integer) result.get("code");
      if ((code == null) || (code.intValue() != 0)) {
        throw new Exception((String) result.get("message"));
      }
      return result;
    } catch (Exception e) {
      throw new Exception("返回结果异常,response:" + response, e);
    }
  }
  public String service(String serviceUrl, HttpParamers paramers) throws Exception {
    return service(serviceUrl, paramers, null);
  }
  public String service(String serviceUrl, HttpParamers paramers, HttpHeader header) throws Exception {
    String url = this.serverUrl + serviceUrl;
    String responseData = "";
    try {
      responseData = HttpClient.doService(url, paramers, header, this.connectTimeout, this.readTimeout);
    } catch (Exception e) {
      throw new Exception(e.getMessage(), e);
    }
    return responseData;
  }

  public String getServerUrl() {
    return this.serverUrl;
  }

  public int getConnectTimeout() {
    return this.connectTimeout;
  }

  public int getReadTimeout() {
    return this.readTimeout;
  }

  public void setConnectTimeout(int connectTimeout) {
    this.connectTimeout = connectTimeout;
  }

  public void setReadTimeout(int readTimeout) {
    this.readTimeout = readTimeout;
  }
}

测试例子Test1.java

package demo;

import org.junit.Ignore;
import org.junit.Test;

public class Test1 {

  //免费的在线REST服务, 提供测试用的HTTP请求假数据
  //接口信息说明可见:http://www.hangge.com/blog/cache/detail_2020.html
  String uri = "http://jsonplaceholder.typicode.com";

  //get方式请求数据
  //请求地址:http://jsonplaceholder.typicode.com/posts
  @Ignore("暂时忽略")
  @Test
  public void test1() {
    System.out.print("\n" + "test1---------------------------"+ "\n");
    HttpParamers paramers = HttpParamers.httpGetParamers();
    String response = "";
    try {
      HttpService httpService = new HttpService(uri);
      response = httpService.service("/posts", paramers);
    } catch (Exception e) {
      e.printStackTrace();
    }
    System.out.print(response);
  }

  //get方式请求数据
  //请求地址:http://jsonplaceholder.typicode.com/posts?userId=5
  @Ignore("暂时忽略")
  @Test
  public void test2() {
    System.out.print("\n" + "test2---------------------------"+ "\n");
    HttpParamers paramers = HttpParamers.httpGetParamers();
    paramers.addParam("userId", "5");
    String response = "";
    try {
      HttpService httpService = new HttpService(uri);
      response = httpService.service("/posts", paramers);
    } catch (Exception e) {
      e.printStackTrace();
    }
    System.out.print(response);
  }

  //post方式请求数据
  //请求地址:http://jsonplaceholder.typicode.com/posts
  @Test
  public void test3() {
    System.out.print("\n" + "test3---------------------------"+ "\n");
    HttpParamers paramers = HttpParamers.httpPostParamers();
    paramers.addParam("time", String.valueOf(System.currentTimeMillis()));
    String response = "";
    try {
      HttpService httpService = new HttpService(uri);
      response = httpService.service("/posts", paramers);
    } catch (Exception e) {
      e.printStackTrace();
    }
    System.out.print(response);
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • java 伪造http请求ip地址的方法

    最近做接口开发,需要跟第三方系统对接接口,基于第三方系统接口的保密性,需要将调用方的请求IP加入到他们的白名单中.由于我们公司平常使用的公网的IP是不固定的,每次都需要将代码提交到固定的服务器上(服务器IP加入了第三方系统的白名单),频繁的修改提交合并代码和启动服务器造成了额外的工作量,给接口联调带来了很大的阻碍. 正常的http请求 我们正常发起一个http的请求如下: import org.apache.http.HttpEntity; import org.apache.http.clie

  • Java如何跳过https的ssl证书验证详解

    打开我们首页,明显看到链接是https打头,https和http的通信协议差别,在于https安全性更高: http和https的差别 很明显,二者最大的区别在于https多了一个ssl证书验证,可以说https是身披SSL外壳的http.因为http存在如下缺陷: 1)通信使用明文,内容可能被窃听(重要密码泄露) 2)不验证通信方身份,有可能遭遇伪装(跨站点请求伪造) 3)无法证明报文的完整性,有可能已遭篡改(运营商劫持) 而https是利用SSL/TLS建立全信道,加密数据包.HTTPS使用

  • JAVA发送http get/post请求,调用http接口、方法详解

    三个例子 -JAVA发送http get/post请求,调用http接口.方法 例1:使用 HttpClient (commons-httpclient-3.0.jar jar下载地址:http://xiazai.jb51.net/201904/yuanma/commons-httpclient-3.0.rar import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOE

  • Java Http请求传json数据乱码问题的解决

    业务场景:调easyui的dialog打开一个弹窗,传参是用json封装的,而且有中文,然后在极速模式是正常的,在ie11测试发现中文出现乱码了 var params = JSON.stringify(writParamList); top.dialog({ id: 'noticeList', title:'列表', width:900, height:500, url:'${root}/notice/multiNoticeList.do?params='+params, onclose:fun

  • 如何使用HttpClient发送java对象到服务器

    这篇文章主要介绍了如何使用HttpClient发送java对象到服务器,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 一.首先导入apache依赖的pom文件包 <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> </dependency> 二.创建

  • Java中Http连接的两种方式(小结)

    在java中连接http,介绍两种方法,一种是java的HttpUrlConnection,另一种是apacha公司的httpClient,后者是第三方的类库需要从外部,导入,同时这也是第一次使用外部的类库,以后还会有很多需要导入外部类库的需求. http协议是基于tcp的一种协议. tcp是一种保证可靠连接的传输协议,通过三次握手,和丢失重传的机制保证数据的传输. 首先来看HttpUrlConnection 这个类是java自带的,直接import就行. 使用tcp连接的过程几乎都一样,htt

  • java httpclient设置超时时间和代理的方法

    设置超时时间 设置HttpClient的超时时间,非常有必要性,因为httpclient 默认超时时间很长,自己可以测试一下是多久,设置超时时间否则会影响自己系统的业务逻辑,例如阻塞系统,影响系统的吞吐量,占用线程数. httpclient 4.4版本之后将这些设置封装到 RequestConfig 对象里,其中 setConnectTimeout 是设置连接到目标 URL 的等待时长,超过这个时间还没连上就抛出连接超时: setConnectionRequestTimeout 是从connec

  • 在java中http请求带cookie的例子

    如下所示: String urlPath = "你的请求链接"; String cookie = "要发送的cookie"; URL url = new URL(urlPath); URLConnection conn = url.openConnection(); conn.setRequestProperty("Cookie", cookie); conn.setDoInput(true); BufferedReader br = new B

  • Java http请求封装工具类代码实例

    java实现http请求的方法常用有两种,一种则是通过java自带的标准类HttpURLConnection去实现,另一种是通过apache的httpclient去实现. 本文用httpclient去实现,需要导入httpclient和httpcore两个jar包,测试时用的httpclient-4.5.1和httpcore-4.4.3. HttpMethod.java package demo; public enum HttpMethod { GET, POST; } HttpHeader.

  • java多媒体文件编码 处理工具类代码实例

    这篇文章主要介绍了java多媒体文件编码 处理工具类使用解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 引入 <dependency> <groupId>org.apache.storm</groupId> <artifactId>storm-core</artifactId> <version>1.1.0</version> </dependency>

  • java实体对象与Map之间的转换工具类代码实例

    这篇文章主要介绍了java实体对象与Map之间的转换工具类代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 Map接口中键和值一一映射. 可以通过键来获取值. 给定一个键和一个值,你可以将该值存储在一个Map对象. 之后,你可以通过键来访问对应的值. 当访问的值不存在的时候,方法就会抛出一个NoSuchElementException异常. 当对象的类型和Map里元素类型不兼容的时候,就会抛出一个 ClassCastException异常

  • Java JDBC自定义封装工具类的步骤和完整代码

    封装JDBC工具类的作用可以优化代码,提高开发效率 步骤 ① 创建配置文件(config.properties),用于存放注册驱动和连接数据库时所需要的参数值 ② 自定义一个类(JDBCUtils.java) ③ 实现构造私有方法 private JDBCUtils(){} ④ 声明所需要的配置变量 private static String driverClass; private static String url; private static String username; priva

  • Java 中DateUtils日期工具类的实例详解

    Java 中DateUtils日期工具类的实例详解 介绍 在java中队日期类型的处理并不方便,通常都需要借助java.text.SimpleDateFormat类来实现日期类型 和字符串类型之间的转换,但是在jdk1.8之后有所改善,jdk1.7以及之前的版本处理日期类型并不方便, 可以借助Joda Time组件来处理,尤其是日期类型的一些数学操作就更是不方便. java代码 /** * * 日期工具类 java对日期的操作一直都很不理想,直到jdk1.8之后才有了本质的改变. * 如果使用的

  • Java实现的汉语拼音工具类完整实例

    本文实例讲述了Java实现的汉语拼音工具类.分享给大家供大家参考,具体如下: package test; import net.sourceforge.pinyin4j.PinyinHelper; import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType; import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat; import net.sourceforge.piny

  • Java实现的zip工具类完整实例

    本文实例讲述了Java实现的zip工具类.分享给大家供大家参考,具体如下: 实现把zip解压到指定路径,把文件夹压缩到zip,把文件列表压缩为zip的三个方法 import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream;

  • springboot封装JsonUtil,CookieUtil工具类代码实例

    这篇文章主要介绍了springboot封装JsonUtil,CookieUtil工具类过程解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 JsonUtil public class JsonUtil { private static ObjectMapper objectMapper = new ObjectMapper(); public static String objectToString(Object object) throws

  • java联调生成测试数据工具类方式

    目录 java联调生成测试数据工具类 代码 java druid工具类及测试 总结 java联调生成测试数据工具类 在日常的联调中,我们经常需要准备一定数量的测试数据,用来配合前端测试. 当然对于简单的数据类型完全可以通过 JDK 自带的 Random 类来实现. 但是参数的格式有特殊要求的时候,临时处理比较麻烦,这个时候就需要借助一些现存的工具类生成测试数据. 代码 import java.math.BigDecimal; import java.text.ParseException; im

  • java公众平台通用接口工具类HttpConnectUtil实例代码

    实例如下: package com.common.util; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.ConnectException; import java.net.HttpURLConnection; import java.net.URL; import

随机推荐