java Http请求

Java HTTP请求

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HeaderElement;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;

public class HttpHelper {

	public static String postRequest(String url, Map<String, String> parameters) throws Exception {

		DefaultHttpClient httpclient = new DefaultHttpClient();
		httpclient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 3000);
		httpclient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 3000);
		httpclient.setHttpRequestRetryHandler(new DefaultHttpRequestRetryHandler(0, false));
		HttpPost httpPost = new HttpPost(url);
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		for (String key : parameters.keySet()) {
			nvps.add(new BasicNameValuePair(key, (String) parameters.get(key)));
		}
		//UrlEncodedFormEntity   将请求参数格式化为 http请求需要的格式
		httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
		httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
		
		
		String charset = "utf-8";
		InputStream is = null;
		BufferedReader br = null;
		try {
			HttpResponse response = httpclient.execute(httpPost);
			HttpEntity entity = response.getEntity();
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode != 200) {
				System.err.println("Method failed: " + response.getStatusLine().getStatusCode());
				System.err.println("Http服务链路异常:服务器状态码为" + statusCode);
			}
			String responseCharSet = getContentCharSet(entity);
			if ("ISO-8859-1".equals(responseCharSet)) {
				charset = responseCharSet;
			}
			StringBuffer buf = new StringBuffer();// 拼接返回的字符串
			if (entity != null) {
				is = entity.getContent();
				// 转换为字节输入流
				br = new BufferedReader(new InputStreamReader(is, charset));
				String body = null;
				while ((body = br.readLine()) != null) {
					buf.append(body);
				}
			}
			return buf.toString();
		} catch (Exception e) {
			throw e;
		} finally {
			if (is != null) {
                                //IO流一定要关闭  不然会耗费资源
				is.close();
				httpPost.releaseConnection();
			}
			if(br != null) {
				br.close();
			}
		}
	}

        //获取请求连接的编码格式
	private static String getContentCharSet(final HttpEntity entity) {

		if (entity == null) {
			throw new IllegalArgumentException("HTTP entity may not be null");
		}
		String charset = null;
		if (entity.getContentType() != null) {
			HeaderElement values[] = entity.getContentType().getElements();
			if (values.length > 0) {
				NameValuePair param = values[0].getParameterByName("charset");
				if (param != null) {
					charset = param.getValue();
				}
			}
		}
		return charset;
	}

}

  

猜你喜欢

转载自www.cnblogs.com/staticking/p/9044513.html