java httpclient 使用_java之HttpClient简单使用

本文介绍了如何使用Java通过Apache HttpClient库进行HTTP和HTTPS的GET、POST请求,包括设置连接池、处理响应内容,以及SSL连接的配置。示例代码详细展示了请求的构造和执行过程。
摘要由CSDN通过智能技术生成

最近在做微信公众号开发,需要用java代码访问微信端接口来请求数据。

由于博主java的网络通信也不是很精通,只是粗略了解皮毛,等以后知识上来了再深入研究java的网络编程。

所以这篇文章就先介绍简单使用。

需要的jar包:

org.apache.httpcomponents

httpclient

4.3.6

org.apache.httpcomponents

httpcore

4.4

本篇博客分为几块部分:http的get、post请求,https的get、post请求

新建一个类HttpUtil:

public class HttpUtil {

private static PoolingHttpClientConnectionManager connMgr;

private static RequestConfig requestConfig;

private static final int MAX_TIMEOUT = 7000;

static {

// 设置连接池

connMgr = new PoolingHttpClientConnectionManager();

// 设置连接池大小

connMgr.setMaxTotal(100);

connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal());

RequestConfig.Builder configBuilder = RequestConfig.custom();

// 设置连接超时

configBuilder.setConnectTimeout(MAX_TIMEOUT);

// 设置读取超时

configBuilder.setSocketTimeout(MAX_TIMEOUT);

// 设置从连接池获取连接实例的超时

configBuilder.setConnectionRequestTimeout(MAX_TIMEOUT);

// 在提交请求之前 测试连接是否可用

configBuilder.setStaleConnectionCheckEnabled(true);

requestConfig = configBuilder.build();

}

}

http部分

get请求:

/**

* 发送 GET 请求(HTTP),不带输入数据

*

* @param url

* @return

*/

public static String doGet(String url) {

return doGet(url, new HashMap());

}

/**

* 发送 GET 请求(HTTP),K-V形式

*

* @param url

* @param params

* @return

*/

public static String doGet(String url, Map params) {

String apiUrl = url;

StringBuffer param = new StringBuffer();

//拼接get请求参数

int i = 0;

for (String key : params.keySet()) {

if (i == 0)

param.append("?");

else

param.append("&");

param.append(key).append("=").append(params.get(key));

i++;

}

//往url后面添加所有的请求参数

apiUrl += param;

String result = null;

//开始执行get请求,新建一个DefaultHttpClient对象

HttpClient httpclient = new DefaultHttpClient();

try {

//新建一个处理特定url的HttpGet对象

HttpGet httpGet = new HttpGet(apiUrl);

//执行请求,得到response对象

HttpResponse response = httpclient.execute(httpGet);

//获取响应状态码

int statusCode = response.getStatusLine().getStatusCode();

System.out.println("执行状态码 : " + statusCode);

HttpEntity entity = response.getEntity();

if (entity != null) {

//处理结果

// result = EntityUtils.toString(entity, "UTF-8");

InputStream instream = entity.getContent();

result = inputStream2String(instream, "UTF-8");

}

} catch (IOException e) {

e.printStackTrace();

}

return result;

}

inputStream2String:

private static String inputStream2String(InputStream is, String encode) {

String result = "";

try {

if (encode == null || encode.equals("")) {

// 默认以utf-8形式

encode = "utf-8";

}

BufferedReader reader = new BufferedReader(new InputStreamReader(is, encode));

StringBuffer sb = new StringBuffer();

while ((result = reader.readLine()) != null) {

sb.append(result).append("\n");

}

return sb.toString();

} catch (UnsupportedEncodingException e1) {

e1.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

return result;

}

post请求:

/**

* 发送 POST 请求(HTTP),不带输入数据

*

* @param apiUrl

* @return

*/

public static String doPost(String apiUrl) {

return doPost(apiUrl, new HashMap());

}

/**

* 发送 POST 请求(HTTP),K-V形式

*

* @param apiUrl

* API接口URL

* @param params

* 参数map

* @return

*/

public static String doPost(String apiUrl, Map params) {

//新建一个可以关闭的httpClient对象

CloseableHttpClient httpClient = HttpClients.createDefault();

String httpStr = null;

//新建一个处理特定请求的httpPost对象

HttpPost httpPost = new HttpPost(apiUrl);

//可以关闭的HttpResponse

CloseableHttpResponse response = null;

try {

//post请求设置

httpPost.setConfig(requestConfig);

//参数键值对对象(NameValuePair)的List

List pairList = new ArrayList(params.size());

for (Map.Entry entry : params.entrySet()) {

NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue().toString());

pairList.add(pair);

}

//设置请求实体(参数)

httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("UTF-8")));

//执行请求

response = httpClient.execute(httpPost);

System.out.println(response.toString());

//获取响应实体

HttpEntity entity = response.getEntity();

//将响应实体以字符串形式变成结果

httpStr = EntityUtils.toString(entity, "UTF-8");

} catch (IOException e) {

e.printStackTrace();

} finally {

if (response != null) {

try {

//关闭流

EntityUtils.consume(response.getEntity());

} catch (IOException e) {

e.printStackTrace();

}

}

}

return httpStr;

}

/**

* 发送 POST 请求(HTTP),JSON形式

*

* @param apiUrl

* @param json

* json对象

* @return

*/

public static String doPost(String apiUrl, Object json) {

CloseableHttpClient httpClient = HttpClients.createDefault();

String httpStr = null;

HttpPost httpPost = new HttpPost(apiUrl);

CloseableHttpResponse response = null;

//大体过程和上面类似

try {

httpPost.setConfig(requestConfig);

StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");// 解决中文乱码问题

stringEntity.setContentEncoding("UTF-8");

//内容类型设置成json格式

stringEntity.setContentType("application/json");

httpPost.setEntity(stringEntity);

response = httpClient.execute(httpPost);

HttpEntity entity = response.getEntity();

System.out.println(response.getStatusLine().getStatusCode());

httpStr = EntityUtils.toString(entity, "UTF-8");

} catch (IOException e) {

e.printStackTrace();

} finally {

if (response != null) {

try {

EntityUtils.consume(response.getEntity());

} catch (IOException e) {

e.printStackTrace();

}

}

}

return httpStr;

}

HTTPS

我新建了一个类SSLClient:

import java.security.cert.CertificateException;

import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;

import javax.net.ssl.TrustManager;

import javax.net.ssl.X509TrustManager;

import org.apache.http.conn.ClientConnectionManager;

import org.apache.http.conn.HttpClientConnectionManager;

import org.apache.http.conn.scheme.Scheme;

import org.apache.http.conn.scheme.SchemeRegistry;

import org.apache.http.conn.ssl.SSLSocketFactory;

import org.apache.http.impl.client.DefaultHttpClient;

//用于进行Https请求的HttpClient

public class SSLClient extends DefaultHttpClient{

public SSLClient() throws Exception{

super();

SSLContext ctx = SSLContext.getInstance("TLS");

X509TrustManager tm = new X509TrustManager() {

public void checkClientTrusted(X509Certificate[] chain,

String authType) throws CertificateException {

}

public void checkServerTrusted(X509Certificate[] chain,

String authType) throws CertificateException {

}

public X509Certificate[] getAcceptedIssuers() {

return null;

}

};

ctx.init(null, new TrustManager[]{tm}, null);

//当前对象的管理

ClientConnectionManager ccm = this.getConnectionManager();

SchemeRegistry sr = ccm.getSchemeRegistry();//当前管理者的注册方案

//SSL工厂

SSLSocketFactory ssf = new SSLSocketFactory(ctx,SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

sr.register(new Scheme("https", 443, ssf));//注册SSL

}

}

get请求:

/**

* 发送get请求

*

* @param url

* 链接地址

* @param charset

* 字符编码,若为null则默认utf-8

* @return

*/

public static String doGetSSL(String url, String charset) {

if (null == charset) {

charset = "utf-8";

}

HttpClient httpClient = null;

HttpGet httpGet = null;

String result = null;

try {

httpClient = new SSLClient();

httpGet = new HttpGet(url);

HttpResponse response = httpClient.execute(httpGet);

if (response != null) {

HttpEntity resEntity = response.getEntity();

if (resEntity != null) {

result = EntityUtils.toString(resEntity, charset);

}

}

} catch (Exception e) {

e.printStackTrace();

}

return result;

}

post请求:

/**

* 发送 SSL POST 请求(HTTPS),K-V形式

*

* @param apiUrl

* API接口URL

* @param params

* 参数map

* @return

*/

public static String doPostSSL(String apiUrl, Map params){

//会发生unable to find valid certification path to requested target异常

//CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory())

//.setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();

HttpPost httpPost = new HttpPost(apiUrl);

CloseableHttpResponse response = null;

String httpStr = null;

SSLClient httpClient = null;

try {

httpClient = new SSLClient();

httpPost.setConfig(requestConfig);

List pairList = new ArrayList(params.size());

for (Map.Entry entry : params.entrySet()) {

NameValuePair pair = new BasicNameValuePair(entry.getKey(), entry.getValue().toString());

pairList.add(pair);

}

httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("utf-8")));

response = httpClient.execute(httpPost);

int statusCode = response.getStatusLine().getStatusCode();

if (statusCode != HttpStatus.SC_OK) {

return null;

}

HttpEntity entity = response.getEntity();

if (entity == null) {

return null;

}

httpStr = EntityUtils.toString(entity, "utf-8");

} catch (Exception e) {

e.printStackTrace();

} finally {

if (response != null) {

try {

EntityUtils.consume(response.getEntity());

} catch (IOException e) {

e.printStackTrace();

}

}

}

return httpStr;

}

/**

* 发送 SSL POST 请求(HTTPS),JSON形式

*

* @param apiUrl

* API接口URL

* @param json

* JSON对象

* @return

*/

public static String doPostSSL(String apiUrl, Object json) {

//CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(createSSLConnSocketFactory())

//.setConnectionManager(connMgr).setDefaultRequestConfig(requestConfig).build();

HttpPost httpPost = new HttpPost(apiUrl);

CloseableHttpResponse response = null;

String httpStr = null;

SSLClient httpClient = null;

try {

httpClient = new SSLClient();

httpPost.setConfig(requestConfig);

StringEntity stringEntity = new StringEntity(json.toString(), "UTF-8");// 解决中文乱码问题

stringEntity.setContentEncoding("UTF-8");

stringEntity.setContentType("application/json");

httpPost.setEntity(stringEntity);

response = httpClient.execute(httpPost);

int statusCode = response.getStatusLine().getStatusCode();

if (statusCode != HttpStatus.SC_OK) {

return null;

}

HttpEntity entity = response.getEntity();

if (entity == null) {

return null;

}

httpStr = EntityUtils.toString(entity, "utf-8");

} catch (Exception e) {

e.printStackTrace();

} finally {

if (response != null) {

try {

EntityUtils.consume(response.getEntity());

} catch (IOException e) {

e.printStackTrace();

}

}

}

return httpStr;

}

以上方法都属于HttpUtil类中。

SSL部分不涉及具体证书的使用。

还有很多不懂请见谅。只知道大概怎么用,大体的意思是知道的。

代码片段:

好的,我会为您介绍Java使用CloseableHttpClient发送HTTP请求的方法。 CloseableHttpClient是Apache HttpClient库中的一个类,它提供了一种发送HTTP请求的简单方法。下面是一些基本的使用方法: 1. 创建CloseableHttpClient对象 ```java CloseableHttpClient httpClient = HttpClients.createDefault(); ``` 2. 创建HttpRequest对象 HttpRequest是一个接口,它定义了HTTP请求的各种方法和属性。在使用CloseableHttpClient发送HTTP请求之前,我们需要先创建一个HttpRequest对象。常用的HttpRequest实现类有HttpGet、HttpPost、HttpPut、HttpDelete等,具体选择哪种实现类取决于你要发送的HTTP请求的类型。 例如,我们可以创建一个HttpGet对象: ```java HttpGet httpGet = new HttpGet("http://www.example.com"); ``` 3. 执行HTTP请求 创建好HttpRequest对象之后,我们就可以使用CloseableHttpClient对象来执行HTTP请求了。执行HTTP请求的方式很简单,只需要调用CloseableHttpClient对象的execute方法,并传入HttpRequest对象即可。 例如,我们可以执行上面创建的HttpGet对象: ```java CloseableHttpResponse response = httpClient.execute(httpGet); ``` 4. 处理HTTP响应 执行HTTP请求之后,我们需要处理HTTP响应。CloseableHttpResponse是一个接口,它定义了HTTP响应的各种方法和属性。我们可以使用这些方法来获取HTTP响应的状态码、响应头、响应体等信息。 例如,我们可以获取HTTP响应的状态码: ```java int statusCode = response.getStatusLine().getStatusCode(); ``` 5. 关闭CloseableHttpClient对象 最后,我们需要关闭CloseableHttpClient对象。关闭CloseableHttpClient对象可以释放与之相关的资源,例如HTTP连接、线程等。我们可以使用CloseableHttpClient对象的close方法来关闭它。 例如: ```java httpClient.close(); ``` 以上就是使用CloseableHttpClient发送HTTP请求的基本方法。希望能对您有所帮助。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值