文档章节

HttpUtil

无知的小孩
 无知的小孩
发布于 2017/09/14 14:04
字数 382
阅读 6
收藏 1

<dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.3</version>
        </dependency>

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
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.client.protocol.HttpClientContext;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient; 
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class HttpUtil {

	static String charset = "UTF-8";

	static Header[] headers = null;
	static CloseableHttpClient httpClient = null;
	static HttpClientContext context = null;
	static BasicCookieStore cookieStore = null;
	static RequestConfig requestConfig = null;

	private HttpUtil() {
	}

	static {
		init();
	}

	static void init() {
		context = HttpClientContext.create();
		cookieStore = new BasicCookieStore();
		requestConfig = RequestConfig.custom().build();
		httpClient = HttpClients.createDefault();
	}

	public static void addCookie(String name, String value, String domain,
			String path) {
		BasicClientCookie cookie = new BasicClientCookie(name, value);
		cookie.setDomain(domain);
		cookie.setPath(path);
		cookieStore.addCookie(cookie);
	}

	public static String get(String uri) throws UnsupportedEncodingException,
			ClientProtocolException, ParseException, URISyntaxException,
			IOException {
		HttpGet get = new HttpGet(uri);
		if (headers != null) {
			get.setHeaders(headers);
		}
		CloseableHttpResponse res = httpClient.execute(get);
		if (200 == res.getStatusLine().getStatusCode()) {
			return EntityUtils.toString(res.getEntity(), charset);
		} else {
			System.out.println("请求失败!" + res.getStatusLine().getStatusCode());
		}
		return "";
	}

	public static String get(String uri, Map<String, String> header)
			throws UnsupportedEncodingException, ClientProtocolException,
			ParseException, URISyntaxException, IOException {
		HttpGet get = new HttpGet(uri);
		if (headers != null) {
			get.setHeaders(headers);
		}
		for (String key : header.keySet()) {
			get.setHeader(key, header.get(key));
		}
		headers = get.getAllHeaders();
		CloseableHttpResponse res = httpClient.execute(get);
		if (200 == res.getStatusLine().getStatusCode()) {
			return EntityUtils.toString(res.getEntity(), charset);
		} else {
			System.out.println("请求失败!" + res.getStatusLine().getStatusCode());
		}
		return "";
	}

	public static String post(String uri, Map<String, String> header,
			Map<String, String> params) throws UnsupportedEncodingException,
			ClientProtocolException, ParseException, URISyntaxException,
			IOException {

		ArrayList<NameValuePair> pairs = new ArrayList<NameValuePair>();
		for (Map.Entry<String, String> param : params.entrySet()) {
			pairs.add(new BasicNameValuePair(param.getKey(), param.getValue()));
		}
		HttpPost post = new HttpPost(uri);
		if (headers != null) {
			post.setHeaders(headers);
		}
		for (String key : header.keySet()) {
			post.setHeader(key, header.get(key));
		}
		headers = post.getAllHeaders();
		CloseableHttpResponse res = httpClient.execute(post);
		if (200 == res.getStatusLine().getStatusCode()) {
			return EntityUtils.toString(res.getEntity(), charset);
		} else {
			System.out.println("请求失败!" + res.getStatusLine().getStatusCode());
		}
		return "";
	}

	public static String post(String uri, Map<String, String> params)
			throws UnsupportedEncodingException, ClientProtocolException,
			ParseException, URISyntaxException, IOException {

		ArrayList<NameValuePair> pairs = new ArrayList<NameValuePair>();
		for (Map.Entry<String, String> param : params.entrySet()) {
			pairs.add(new BasicNameValuePair(param.getKey(), param.getValue()));
		}
		HttpPost post = new HttpPost(uri);
		UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs, charset);
		// 设置post求情参数
		post.setEntity(entity);
		if (headers != null) {
			post.setHeaders(headers);
		}
		CloseableHttpResponse res = httpClient.execute(post);
		if (200 == res.getStatusLine().getStatusCode()) {
			return EntityUtils.toString(res.getEntity(), charset);
		} else {
			System.out.println("请求失败!" + res.getStatusLine().getStatusCode());
		}
		return "";
	} 
}

 

© 著作权归作者所有

共有 人打赏支持
无知的小孩
粉丝 1
博文 70
码字总数 19034
作品 0
贵阳
后端工程师
私信 提问

暂无文章

如何开发一款以太坊(安卓)钱包系列2 - 导入账号及账号管理

这是如何开发一款以太坊(安卓)钱包系列第2篇,如何导入账号。有时用户可能已经有一个账号,这篇文章接来介绍下,如何实现导入用户已经存在的账号。 导入账号预备知识 从用户需求上来讲,导...

Tiny熊
今天
2
0
intellJ IDEA搭建java+selenium自动化环境(maven,selenium,testng)

1.安装jdk1.8; 2.安装intellJ; 3.安装maven; 3.1 如果是单前用户,配置用户环境变量即可,如果是多用户,则需配置系统环境变量,变量名为MAVEN_HOME,赋值D:\Application\maven,往path中...

不最醉不龟归
今天
3
0
聊聊ShenandoahGC的Brooks Pointers

序 本文主要研究一下ShenandoahGC的Brooks Pointers Shenandoah Shenandoah面向low-pause-time的垃圾收集器,它的GC cycle主要有 Snapshot-at-the-beginning concurrent mark包括Init Mark(P......

go4it
昨天
2
0
Makefile通用编写规则

#简单实用的Makefile模板: objs := a.o b.o test:$(objs) gcc -o test $^ # .a.o.d .b.o.d dep_files := $(foreach f,$(objs),.$(f).d) dep_files := $(wildcard $(dep_files)) ifneq ($(d......

shzwork
昨天
2
0
《万历十五年》的读后感作文4000字

《万历十五年》的读后感作文4000字: 万历十五年,即1587年,距今已过去432年。在明朝276的历史中,这一年很平淡,并没有什么特别之处。黄仁宇的《万历十五年》一书,有别于其他的历史叙述方...

原创小博客
昨天
1
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部