http://hc.apache.org/
阿帕奇的开源项目。用于Http通信。
<dependency>
	<groupId>org.apache.httpcomponents</groupId>
	<artifactId>httpclient</artifactId>
	<version>4.5.1</version>
</dependency>

1.client

org.apache.http.client.HttpClient
接口。
CloseableHttpClient org.apache.http.impl.client.HttpClients.createDefault()
此方法可以拿到HttpClient对象。它是线程安全的。

2.request

org.apache.http.HttpRequest
接口。实现类有HttpGet、HttpPost等。
org.apache.http.client.methods.HttpUriRequest
继承了HttpRequest接口的接口。
void org.apache.http.message.AbstractHttpMessage.addHeader(String name, String value)
添加请求的头部信息。
org.apache.http.client.methods.HttpGet
代表HttpGet请求。
org.apache.http.client.methods.HttpPost
代表HttpPost请求。

2.1 get请求

org.apache.http.client.methods.HttpGet.HttpGet(String uri)
HttpGet请求的构造函数。

2.2 post请求

org.apache.http.client.methods.HttpPost.HttpPost(String uri)
HttpPost请求的构造函数。
org.apache.http.entity.StringEntity.StringEntity(String string) 
http报文body的格式是字符串。用于构造json、xml类post请求。

3.设置参数

Builder org.apache.http.client.config.RequestConfig.custom()
拿到builder。
Builder org.apache.http.client.config.RequestConfig.Builder.setSocketTimeout(int socketTimeout)
设置socket链接超时。
Builder org.apache.http.client.config.RequestConfig.Builder.setConnectionTimeout(int connectionRequestTimeout)
设置http连接超时。socket超时是http超时的充分不必要条件。
Builder org.apache.http.client.config.RequestConfig.Builder.setConnectionRequestTimeout(int connectionRequestTimeout)
设置请求发出前的超时时间。适用于用连接池,连接池占满的情况。
RequestConfig org.apache.http.client.config.RequestConfig.Builder.build()
至此拿到了RequestConfig 对象。
void org.apache.http.client.methods.HttpRequestBase.setConfig(RequestConfigconfig)
设置连接超时等在内的参数。RequestConfig对象的生成见下行。
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(2000).build();

4.execute

CloseableHttpResponse org.apache.http.impl.client.CloseableHttpClient.execute(HttpUriRequest request) 
执行请求并返回结果,是同步函数,需要等待。

5.response

org.apache.http.client.methods.CloseableHttpResponse
接口。
StatusLine org.apache.http.HttpResponse.getStatusLine()
获取状态栏。
HttpEntity org.apache.http.HttpResponse.getEntity()
获取消息实体。
InputStream org.apache.http.HttpEntity.getContent()
获取内容。如果是文本数据,通常这样来拿。
 
Scanner scanner = new Scanner(instream, "utf-8");

void org.apache.http.util.EntityUtils.consume(HttpEntity entity) 
调用HttpEntity.getContent()就得到了InputStream,此方法用于把流消费完,然后关掉这个InputStream。

6. 常见问题

中文乱码. 
需要 header 加入 Content-Type: text/plain; charset=UTF-8.
代码为:
httpPost.setEntity(new StringEntity(content, ContentType.create("text/plain", Charset.forName("UTF-8"))));

7.代码

//httpcomponents-client-4.3.6
package org.apache.http.examples.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class HttpComponentsQuickStart {

	public static void main(String[] args) throws Exception {
		httpGet();
		httpPost();
	}
	
    //http的get请求
	static void httpGet() throws ClientProtocolException, IOException {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		CloseableHttpResponse response1 = null;
		try {
			HttpGet httpGet = new HttpGet("http://www.sjtu.edu.cn");
			response1 = httpclient.execute(httpGet);
			System.out.println(response1.getStatusLine());
			HttpEntity entity1 = response1.getEntity();
			InputStream instream = entity1.getContent();
			String s = null;
			StringBuilder sb = new StringBuilder();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					instream, "utf-8"));
			while ((s = reader.readLine()) != null) {
				sb.append(s + "\n");
			}
			System.out.println(sb);
			EntityUtils.consume(entity1);
		} finally {
			response1.close();
		}
	}
	
    //http发送Post请求,内容为键值对
	static void httpPost() throws IOException {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost("http://targethost/login");
		List nvps = new ArrayList();
		nvps.add(new BasicNameValuePair("username", "vip"));
		nvps.add(new BasicNameValuePair("password", "secret"));
		httpPost.setEntity(new UrlEncodedFormEntity(nvps));
		CloseableHttpResponse response2 = httpclient.execute(httpPost);
		try {
			System.out.println(response2.getStatusLine());
			HttpEntity entity2 = response2.getEntity();
			EntityUtils.consume(entity2);
		} finally {
			response2.close();
		}
	}
	
	//http发送Post请求,内容为json
	static String httpJsonPost(String json,String url) throws IOException {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);
		//setConnectTimeout
		RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(2000).build();
		httpPost.setConfig(requestConfig);
		httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
		StringEntity se = new StringEntity(json);
		//se.setContentType("text/json");
		httpPost.setEntity(se);
		CloseableHttpResponse response = httpclient.execute(httpPost);
		try {
			HttpEntity entity = response.getEntity();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					entity.getContent(), "utf-8"));
			String s;
			StringBuilder sb=new StringBuilder();
			while ((s = reader.readLine()) != null) {
				sb.append(s + "\n");
			}
			EntityUtils.consume(entity);
			return sb.toString();
		} finally {
			response.close();
		}
	}
	
	//http发送post请求,内容为xml
	static String httpXmlPost(String url,String xml) throws IOException {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);
		httpPost.addHeader(HTTP.CONTENT_TYPE, "application/xml");
		StringEntity se = new StringEntity(xml);
		httpPost.setEntity(se);
		CloseableHttpResponse response = httpclient.execute(httpPost);
		try {
			HttpEntity entity = response.getEntity();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					entity.getContent(), "utf-8"));
			String s;
			StringBuilder sb=new StringBuilder();
			while ((s = reader.readLine()) != null) {
				sb.append(s + "\n");
			}
			EntityUtils.consume(entity);
			return sb.toString();
		} finally {
			response.close();
		}
		}

}
/*
 * HTTP/1.1 200 OK ? 
 *
 *上海交通大学
 * ...
 * 
 * HTTP/1.1 404 Not Found
 */
Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐