1. 程式人生 > >Java利用HttpPost工具類提交資料

Java利用HttpPost工具類提交資料

需求:

最近在網上找了一個weixin的工具包,但是利用在post提交的時候總是出錯,看了下weixin工具包裡面的提交方式是採用httpPost,於是自己也寫了一個專門用於提交資料的工具類

package com.wx.common;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
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.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.riversoft.weixin.common.exception.WxError;
import com.riversoft.weixin.common.exception.WxRuntimeException;

public class HttpUtils {

	private static String charset = "utf-8";
	private static HttpClient httpClient = HttpClients.createDefault();

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static String doPost(String url, Map<String, String> map) {
		HttpPost httpPost = null;
		String result = null;
		try {
			httpPost = new HttpPost(url);
			// 設定引數
			List<NameValuePair> list = new ArrayList<NameValuePair>();
			Iterator iterator = map.entrySet().iterator();
			while (iterator.hasNext()) {
				Entry<String, String> elem = (Entry<String, String>) iterator.next();
				list.add(new BasicNameValuePair(elem.getKey(), elem.getValue()));
			}
			if (list.size() > 0) {
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, charset);
				httpPost.setEntity(entity);
			}
			HttpResponse response = httpClient.execute(httpPost);
			if (response != null) {
				HttpEntity resEntity = response.getEntity();
				if (resEntity != null) {
					result = EntityUtils.toString(resEntity, charset);
				}
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return result;
	}

	public static String doGet(String url) {
		HttpGet httpGet = new HttpGet(url);
		try (CloseableHttpResponse response = (CloseableHttpResponse) httpClient.execute(httpGet)) {
			StatusLine statusLine = response.getStatusLine();
			HttpEntity entity = response.getEntity();
			if (statusLine.getStatusCode() >= 300) {
				EntityUtils.consume(entity);
				throw new WxRuntimeException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
			}
			String responseContent = entity == null ? null : EntityUtils.toString(entity, Consts.UTF_8);

			WxError wxError = WxError.fromJson(responseContent);

			if (wxError.getErrorCode() != 0) {
				throw new WxRuntimeException(wxError);
			}
			return responseContent;
		} catch (IOException ex) {
			throw new WxRuntimeException(999, ex.getMessage());
		}
	}
}