当前位置: 移动技术网 > IT编程>开发语言>Java > JAVA通过HttpClient发送HTTP请求的方法示例

JAVA通过HttpClient发送HTTP请求的方法示例

2019年07月19日  | 移动技术网IT编程  | 我要评论

httpclient介绍

httpclient 不是一个浏览器。它是一个客户端的 http 通信实现库。httpclient的目标是发 送和接收http 报文。httpclient不会去缓存内容,执行 嵌入在 html 页面中的javascript 代码,猜测内容类型,重新格式化请求/重定向uri,或者其它和 http 运输无关的功能。

httpclient使用

使用需要引入jar包,maven项目引入如下:

<dependency>
      <groupid>org.apache.httpcomponents</groupid>
      <artifactid>httpclient</artifactid>
      <version>4.5</version>
    </dependency>

    <dependency>
      <groupid>org.apache.httpcomponents</groupid>
      <artifactid>httpcore</artifactid>
      <version>4.4.4</version>
    </dependency>

    <dependency>
      <groupid>org.apache.httpcomponents</groupid>
      <artifactid>httpmime</artifactid>
      <version>4.5</version>
    </dependency>

使用方法,代码如下: 

package com.test;

import java.io.file;
import java.io.ioexception;
import java.security.keymanagementexception;
import java.security.keystoreexception;
import java.security.nosuchalgorithmexception;
import java.util.iterator;
import java.util.list;
import java.util.map;

import org.apache.http.httpentity;
import org.apache.http.httpstatus;
import org.apache.http.client.config.requestconfig;
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.config.registry;
import org.apache.http.config.registrybuilder;
import org.apache.http.conn.socket.connectionsocketfactory;
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.trustselfsignedstrategy;
import org.apache.http.entity.contenttype;
import org.apache.http.entity.stringentity;
import org.apache.http.entity.mime.multipartentitybuilder;
import org.apache.http.entity.mime.content.filebody;
import org.apache.http.entity.mime.content.stringbody;
import org.apache.http.impl.client.closeablehttpclient;
import org.apache.http.impl.client.defaulthttprequestretryhandler;
import org.apache.http.impl.client.httpclients;
import org.apache.http.impl.conn.poolinghttpclientconnectionmanager;
import org.apache.http.util.entityutils;

/**
 * 
 * @author h__d
 * @date 2016年10月19日 上午11:27:25
 *
 */
public class httpclientutil {

  // utf-8字符编码
  public static final string charset_utf_8 = "utf-8";

  // http内容类型。
  public static final string content_type_text_html = "text/xml";

  // http内容类型。相当于form表单的形式,提交数据
  public static final string content_type_form_url = "application/x-www-form-urlencoded";

  // http内容类型。相当于form表单的形式,提交数据
  public static final string content_type_json_url = "application/json;charset=utf-8";
  

  // 连接管理器
  private static poolinghttpclientconnectionmanager pool;

  // 请求配置
  private static requestconfig requestconfig;

  static {
    
    try {
      //system.out.println("初始化httpclienttest~~~开始");
      sslcontextbuilder builder = new sslcontextbuilder();
      builder.loadtrustmaterial(null, new trustselfsignedstrategy());
      sslconnectionsocketfactory sslsf = new sslconnectionsocketfactory(
          builder.build());
      // 配置同时支持 http 和 htpps
      registry<connectionsocketfactory> socketfactoryregistry = registrybuilder.<connectionsocketfactory> create().register(
          "http", plainconnectionsocketfactory.getsocketfactory()).register(
          "https", sslsf).build();
      // 初始化连接管理器
      pool = new poolinghttpclientconnectionmanager(
          socketfactoryregistry);
      // 将最大连接数增加到200,实际项目最好从配置文件中读取这个值
      pool.setmaxtotal(200);
      // 设置最大路由
      pool.setdefaultmaxperroute(2);
      // 根据默认超时限制初始化requestconfig
      int sockettimeout = 10000;
      int connecttimeout = 10000;
      int connectionrequesttimeout = 10000;
      requestconfig = requestconfig.custom().setconnectionrequesttimeout(
          connectionrequesttimeout).setsockettimeout(sockettimeout).setconnecttimeout(
          connecttimeout).build();

      //system.out.println("初始化httpclienttest~~~结束");
    } catch (nosuchalgorithmexception e) {
      e.printstacktrace();
    } catch (keystoreexception e) {
      e.printstacktrace();
    } catch (keymanagementexception e) {
      e.printstacktrace();
    }
    

    // 设置请求超时时间
    requestconfig = requestconfig.custom().setsockettimeout(50000).setconnecttimeout(50000)
        .setconnectionrequesttimeout(50000).build();
  }

  public static closeablehttpclient gethttpclient() {
    
    closeablehttpclient httpclient = httpclients.custom()
        // 设置连接池管理
        .setconnectionmanager(pool)
        // 设置请求配置
        .setdefaultrequestconfig(requestconfig)
        // 设置重试次数
        .setretryhandler(new defaulthttprequestretryhandler(0, false))
        .build();
    
    return httpclient;
  }

  /**
   * 发送post请求
   * 
   * @param httppost
   * @return
   */
  private static string sendhttppost(httppost httppost) {

    closeablehttpclient httpclient = null;
    closeablehttpresponse response = null;
    // 响应内容
    string responsecontent = null;
    try {
      // 创建默认的httpclient实例.
      httpclient = gethttpclient();
      // 配置请求信息
      httppost.setconfig(requestconfig);
      // 执行请求
      response = httpclient.execute(httppost);
      // 得到响应实例
      httpentity entity = response.getentity();

      // 可以获得响应头
      // header[] headers = response.getheaders(httpheaders.content_type);
      // for (header header : headers) {
      // system.out.println(header.getname());
      // }

      // 得到响应类型
      // system.out.println(contenttype.getordefault(response.getentity()).getmimetype());

      // 判断响应状态
      if (response.getstatusline().getstatuscode() >= 300) {
        throw new exception(
            "http request is not success, response code is " + response.getstatusline().getstatuscode());
      }

      if (httpstatus.sc_ok == response.getstatusline().getstatuscode()) {
        responsecontent = entityutils.tostring(entity, charset_utf_8);
        entityutils.consume(entity);
      }

    } catch (exception e) {
      e.printstacktrace();
    } finally {
      try {
        // 释放资源
        if (response != null) {
          response.close();
        }
      } catch (ioexception e) {
        e.printstacktrace();
      }
    }
    return responsecontent;
  }

  /**
   * 发送get请求
   * 
   * @param httpget
   * @return
   */
  private static string sendhttpget(httpget httpget) {

    closeablehttpclient httpclient = null;
    closeablehttpresponse response = null;
    // 响应内容
    string responsecontent = null;
    try {
      // 创建默认的httpclient实例.
      httpclient = gethttpclient();
      // 配置请求信息
      httpget.setconfig(requestconfig);
      // 执行请求
      response = httpclient.execute(httpget);
      // 得到响应实例
      httpentity entity = response.getentity();

      // 可以获得响应头
      // header[] headers = response.getheaders(httpheaders.content_type);
      // for (header header : headers) {
      // system.out.println(header.getname());
      // }

      // 得到响应类型
      // system.out.println(contenttype.getordefault(response.getentity()).getmimetype());

      // 判断响应状态
      if (response.getstatusline().getstatuscode() >= 300) {
        throw new exception(
            "http request is not success, response code is " + response.getstatusline().getstatuscode());
      }

      if (httpstatus.sc_ok == response.getstatusline().getstatuscode()) {
        responsecontent = entityutils.tostring(entity, charset_utf_8);
        entityutils.consume(entity);
      }

    } catch (exception e) {
      e.printstacktrace();
    } finally {
      try {
        // 释放资源
        if (response != null) {
          response.close();
        }
      } catch (ioexception e) {
        e.printstacktrace();
      }
    }
    return responsecontent;
  }
  
  
  
  /**
   * 发送 post请求
   * 
   * @param httpurl
   *      地址
   */
  public static string sendhttppost(string httpurl) {
    // 创建httppost
    httppost httppost = new httppost(httpurl);
    return sendhttppost(httppost);
  }

  /**
   * 发送 get请求
   * 
   * @param httpurl
   */
  public static string sendhttpget(string httpurl) {
    // 创建get请求
    httpget httpget = new httpget(httpurl);
    return sendhttpget(httpget);
  }
  
  

  /**
   * 发送 post请求(带文件)
   * 
   * @param httpurl
   *      地址
   * @param maps
   *      参数
   * @param filelists
   *      附件
   */
  public static string sendhttppost(string httpurl, map<string, string> maps, list<file> filelists) {
    httppost httppost = new httppost(httpurl);// 创建httppost
    multipartentitybuilder mebuilder = multipartentitybuilder.create();
    if (maps != null) {
      for (string key : maps.keyset()) {
        mebuilder.addpart(key, new stringbody(maps.get(key), contenttype.text_plain));
      }
    }
    if (filelists != null) {
      for (file file : filelists) {
        filebody filebody = new filebody(file);
        mebuilder.addpart("files", filebody);
      }
    }
    httpentity reqentity = mebuilder.build();
    httppost.setentity(reqentity);
    return sendhttppost(httppost);
  }

  /**
   * 发送 post请求
   * 
   * @param httpurl
   *      地址
   * @param params
   *      参数(格式:key1=value1&key2=value2)
   * 
   */
  public static string sendhttppost(string httpurl, string params) {
    httppost httppost = new httppost(httpurl);// 创建httppost
    try {
      // 设置参数
      if (params != null && params.trim().length() > 0) {
        stringentity stringentity = new stringentity(params, "utf-8");
        stringentity.setcontenttype(content_type_form_url);
        httppost.setentity(stringentity);
      }
    } catch (exception e) {
      e.printstacktrace();
    }
    return sendhttppost(httppost);
  }

  /**
   * 发送 post请求
   * 
   * @param maps
   *      参数
   */
  public static string sendhttppost(string httpurl, map<string, string> maps) {
    string parem = convertstringparamter(maps);
    return sendhttppost(httpurl, parem);
  }

  
  
  
  /**
   * 发送 post请求 发送json数据
   * 
   * @param httpurl
   *      地址
   * @param paramsjson
   *      参数(格式 json)
   * 
   */
  public static string sendhttppostjson(string httpurl, string paramsjson) {
    httppost httppost = new httppost(httpurl);// 创建httppost
    try {
      // 设置参数
      if (paramsjson != null && paramsjson.trim().length() > 0) {
        stringentity stringentity = new stringentity(paramsjson, "utf-8");
        stringentity.setcontenttype(content_type_json_url);
        httppost.setentity(stringentity);
      }
    } catch (exception e) {
      e.printstacktrace();
    }
    return sendhttppost(httppost);
  }
  
  /**
   * 发送 post请求 发送xml数据
   * 
   * @param httpurl  地址
   * @param paramsxml 参数(格式 xml)
   * 
   */
  public static string sendhttppostxml(string httpurl, string paramsxml) {
    httppost httppost = new httppost(httpurl);// 创建httppost
    try {
      // 设置参数
      if (paramsxml != null && paramsxml.trim().length() > 0) {
        stringentity stringentity = new stringentity(paramsxml, "utf-8");
        stringentity.setcontenttype(content_type_text_html);
        httppost.setentity(stringentity);
      }
    } catch (exception e) {
      e.printstacktrace();
    }
    return sendhttppost(httppost);
  }
  

  /**
   * 将map集合的键值对转化成:key1=value1&key2=value2 的形式
   * 
   * @param parametermap
   *      需要转化的键值对集合
   * @return 字符串
   */
  public static string convertstringparamter(map parametermap) {
    stringbuffer parameterbuffer = new stringbuffer();
    if (parametermap != null) {
      iterator iterator = parametermap.keyset().iterator();
      string key = null;
      string value = null;
      while (iterator.hasnext()) {
        key = (string) iterator.next();
        if (parametermap.get(key) != null) {
          value = (string) parametermap.get(key);
        } else {
          value = "";
        }
        parameterbuffer.append(key).append("=").append(value);
        if (iterator.hasnext()) {
          parameterbuffer.append("&");
        }
      }
    }
    return parameterbuffer.tostring();
  }

  public static void main(string[] args) throws exception {
    
    system.out.println(sendhttpget("http://www.baidu.com"));
  
  }
}

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网