search
HomeJavajavaTutorialJava method of sending HTTP request through HttpClient
Java method of sending HTTP request through HttpClientSep 26, 2017 am 10:12 AM
httphttpclientjava

This article mainly introduces JAVA method examples of sending HTTP requests through HttpClient. It introduces the use of HttpClient in detail, which has certain reference value. Those who are interested can learn about it

HttpClient Introduction

HttpClient is not a browser. It is a client-side HTTP communication implementation library. The goal of HttpClient is to send and receive HTTP messages. HttpClient does not cache content, execute JavaScript code embedded in HTML pages, guess content types, reformat request/redirect URIs, or other functions unrelated to HTTP transport.

HttpClient use

You need to introduce the jar package. The maven project introduction is as follows:


##

<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>

How to use, the code is as follows:



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"));
  
  }
}

The above is the detailed content of Java method of sending HTTP request through HttpClient. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Springboot怎么使用内置tomcat禁止不安全HTTPSpringboot怎么使用内置tomcat禁止不安全HTTPMay 12, 2023 am 11:49 AM

Springboot内置tomcat禁止不安全HTTP方法1、在tomcat的web.xml中可以配置如下内容让tomcat禁止不安全的HTTP方法/*PUTDELETEHEADOPTIONSTRACEBASIC2、Springboot使用内置tomcat没有web.xml配置文件,可以通过以下配置进行,简单来说就是要注入到Spring容器中@ConfigurationpublicclassTomcatConfig{@BeanpublicEmbeddedServletContainerFacto

JAVA发送HTTP请求的方式有哪些JAVA发送HTTP请求的方式有哪些Apr 15, 2023 am 09:04 AM

1.HttpURLConnection使用JDK原生提供的net,无需其他jar包,代码如下:importcom.alibaba.fastjson.JSON;importjava.io.BufferedReader;importjava.io.InputStream;importjava.io.InputStreamReader;importjava.io.OutputStream;importjava.net.HttpURLConnection;

nginx中如何升级到支持HTTP2.0nginx中如何升级到支持HTTP2.0May 24, 2023 pm 10:58 PM

一、前言#ssl写在443端口后面。这样http和https的链接都可以用listen443sslhttp2default_server;server_namechat.chengxinsong.cn;#hsts的合理使用,max-age表明hsts在浏览器中的缓存时间,includesubdomainscam参数指定应该在所有子域上启用hsts,preload参数表示预加载,通过strict-transport-security:max-age=0将缓存设置为0可以撤销hstsadd_head

使用Java 11中的HttpClient发送HTTP请求并处理响应使用Java 11中的HttpClient发送HTTP请求并处理响应Aug 01, 2023 am 11:48 AM

标题:使用Java11中的HttpClient发送HTTP请求并处理响应引言:在现代的互联网应用程序中,与其他服务器进行HTTP通信是非常常见的任务。Java提供了一些内置的工具,可以帮助我们实现这一目标,其中最新且推荐使用的是Java11中引入的HttpClient类。本文将介绍如何使用Java11中的HttpClient发送HTTP请求并处理响应,

如何使用golang中的http.Client进行HTTP请求的高级操作如何使用golang中的http.Client进行HTTP请求的高级操作Nov 18, 2023 am 11:37 AM

如何使用golang中的http.Client进行HTTP请求的高级操作引言:在现代开发中,HTTP请求是不可避免的一部分。golang提供了强大的标准库,其中包含了http包。http包提供了http.Client结构体,用于发送HTTP请求和接收HTTP响应。在本文中,我们将探讨如何使用http.Client进行HTTP请求的高级操作,并提供具体的代码示

Nginx中HTTP的keepalive怎么配置Nginx中HTTP的keepalive怎么配置May 12, 2023 am 11:28 AM

httpkeepalive在http早期,每个http请求都要求打开一个tpcsocket连接,并且使用一次之后就断开这个tcp连接。使用keep-alive可以改善这种状态,即在一次tcp连接中可以持续发送多份数据而不会断开连接。通过使用keep-alive机制,可以减少tcp连接建立次数,也意味着可以减少time_wait状态连接,以此提高性能和提高httpd服务器的吞吐率(更少的tcp连接意味着更少的系统内核调用,socket的accept()和close()调用)。但是,keep-ali

Python的HTTP客户端模块urllib与urllib3怎么使用Python的HTTP客户端模块urllib与urllib3怎么使用May 20, 2023 pm 07:58 PM

一、urllib概述:urllib是Python中请求url连接的官方标准库,就是你安装了python,这个库就已经可以直接使用了,基本上涵盖了基础的网络请求功能。在Python2中主要为urllib和urllib2,在Python3中整合成了urllib。Python3.x中将urllib2合并到了urllib,之后此包分成了以下四个模块:urllib.request:它是最基本的http请求模块,用来模拟发送请求urllib.error:异常处理模块,如果出现错误可以捕获这些异常urllib

如何使用Java中的httpclient进行重定向和请求转发的比较如何使用Java中的httpclient进行重定向和请求转发的比较Apr 21, 2023 pm 11:43 PM

这里介绍一下:HttpClient4.x版本,get请求方法会自动进行重定向,而post请求方法不会自动进行重定向,这是要注意的地方。我上次发生错误,就是使用post提交表单登录,当时没有自动重定向。请求转发和重定向的区别1、重定向是两次请求,转发是一次请求,因此转发的速度要快于重定向。2、重定向之后地址栏上的地址会发生变化,变化成第二次请求的地址,转发之后地址栏上的地址不会变化,还是第一次请求的地址。3、转发是服务器行为,重定向是客户端行为。重定向时浏览器上的网址改变,转发是浏览器上的网址不变

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools