1. 程式人生 > >java http get post 各種請求,模擬瀏覽器請求

java http get post 各種請求,模擬瀏覽器請求

package com.hlzt.wx.util.http;

import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

import com.hlzt.wx.util.token.GlobalAccessTokenUtils;

public class HttpClientConnectionManager {
 
 
	 // http客戶端
	private static DefaultHttpClient httpclient=new DefaultHttpClient();
	 
	

	public static DefaultHttpClient getHttpclient() {
		return httpclient;
	}


	public static void setHttpclient(DefaultHttpClient httpclient) {
		HttpClientConnectionManager.httpclient = httpclient;
	}
 /**
  * 獲取SSL驗證的HttpClient
  * @param httpClient
  * @return
  *//*
 public static HttpClient getSSLInstance(HttpClient httpClient){
  ClientConnectionManager ccm = httpClient.getConnectionManager();
  SchemeRegistry sr = ccm.getSchemeRegistry();
  sr.register(new Scheme("https", MySSLSocketFactory.getInstance(), 443));
  httpClient =  new DefaultHttpClient(ccm, httpClient.getParams());
  return httpClient;
 }*/
 
 /**
  * 模擬瀏覽器post提交
  * @param url
  * @return
  */
 public static HttpPost getPostMethod(String url) {
  HttpPost pmethod = new HttpPost(url); // 設定響應頭資訊
  pmethod.addHeader("Connection", "keep-alive");
  pmethod.addHeader("Accept", "*/*");
  pmethod.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
  pmethod.addHeader("Host", "mp.weixin.qq.com");
  pmethod.addHeader("X-Requested-With", "XMLHttpRequest");
  pmethod.addHeader("Cache-Control", "max-age=0");
  pmethod.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
  return pmethod;
 }

 /**
  * 模擬瀏覽器GET提交
  * @param url
  * @return
  */
 public static HttpGet getGetMethod(String url) {
  HttpGet pmethod = new HttpGet(url);
  // 設定響應頭資訊
  pmethod.addHeader("Connection", "keep-alive");
  pmethod.addHeader("Cache-Control", "max-age=0");
  pmethod.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
  pmethod.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/;q=0.8");
  return pmethod;
 }
}


package com.hlzt.wx.util.http;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONObject;

import org.apache.commons.collections4.map.LinkedMap;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.EntityBuilder;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;



/**
 * 通過HttpClient訪問,網站的url
 * @author zhouhf
 * @version 1.0 2014年9月24日
 * @since 1.6
 */
public final class WxHttpClientUtils {

	/**
	 * 日誌物件
	 */
	protected static Logger logger = LoggerFactory.getLogger(WxHttpClientUtils.class);
	
	 // http客戶端
		private static DefaultHttpClient httpclient=new DefaultHttpClient();
		 
		

		public static DefaultHttpClient getHttpclient() {
			return httpclient;
		}


		public static void setHttpclient(DefaultHttpClient httpclient) {
			WxHttpClientUtils.httpclient = httpclient;
		}
	
	/**
	 * 嘗試請求指定連結是否正常
	 * @param client 客戶端物件
	 * @param url 請求的連結
	 * @throws HttpException
	 * @throws IOException
	 */
	public static boolean testUrl(String url){
		return testUrl(createHttpClient(),url);
	}
	
	/**
	 * 嘗試請求指定連結是否正常
	 * @param client 客戶端物件
	 * @param url 請求的連結
	 * @throws HttpException
	 * @throws IOException
	 */
	public static boolean testUrl(HttpClient client,String url){
		HttpGet httpGet=new HttpGet(url);
		httpGet.addHeader("Content-Type", "text/html;charset=UTF-8");
		int statusCode = 0;
		try {
			HttpResponse response = client.execute(httpGet);
			statusCode = response.getStatusLine().getStatusCode();
		} catch (Exception e) {
			logger.error("HttpClient請求異常",e);
		} finally{
			httpGet.abort();
		}
		if(HttpStatus.SC_OK != statusCode){
			return false;
		}
		return true;
	}
	
	
	/**
	 * 通過GET方法請求伺服器文字資料
	 * @param url 地址
	 * @param parameters 引數
	 * @return 結果文字
	 * @throws HttpException
	 * @throws IOException
	 */
	public static String httpGetText(String url,LinkedMap<String,Object> parameters) throws HttpException, IOException{
		return httpGetText(createHttpClient(),url,parameters);
	}
	
	/**
	 * 通過GET方法請求伺服器文字資料
	 * @param client http客戶端
	 * @param url 地址
	 * @param parameters 引數
	 * @return 結果文字
	 * @throws HttpException
	 * @throws IOException
	 */
	public static String httpGetText(HttpClient client,String url,LinkedMap<String,Object> parameters) throws HttpException, IOException{
		if(parameters != null && parameters.size() > 0){
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			for(int i=0,len = parameters.size(); i < len; i++){
				Object v = parameters.getValue(i);
				if(v == null)
					continue;
				String value = v.toString();
				String key = parameters.get(i);
				params.add(new BasicNameValuePair(key,value));
			}
			if(url.indexOf("?") > -1){
				url += "&" + URLEncodedUtils.format(params, "UTF-8");
			}else{
				url += "?" + URLEncodedUtils.format(params, "UTF-8");
			}
		}
		HttpGet httpGet=new HttpGet(url);
		httpGet.addHeader("Content-Type", "text/html;charset=UTF-8");
		try{
			HttpResponse response = client.execute(httpGet);
			InputStream  is = response.getEntity().getContent();
			ByteArrayOutputStream os = new ByteArrayOutputStream();
			IOUtils.copy(is,os);
			return new String(os.toByteArray(),"UTF-8");
		}finally{
			httpGet.abort();
		}
		
	}

	/**
	 * 通過POST方式向伺服器傳送資料
	 * @param client http客戶端
	 * @param url 地址
	 * @param parameters 引數集
	 * @param attachs 附件列表
	 * @return 返回結果
	 * @throws HttpException
	 * @throws IOException
	 */
	public static String httpPostUpload(HttpClient client,String url,LinkedMap<String,Object> parameters,LinkedMap<String,File> attachs) throws HttpException, IOException{
		HttpPost httpPost=new HttpPost(url);
		HttpEntity entity = null;
		if(attachs != null && attachs.size() > 0){
			MultipartEntityBuilder multipartBuilder = MultipartEntityBuilder.create();
			multipartBuilder.setCharset(Charset.forName("UTF-8"));
			for(int i = 0,len = attachs.size(); i< len; i++){
				multipartBuilder.addBinaryBody(attachs.get(i), attachs.getValue(i));
			}
			if(parameters != null && parameters.size() > 0){
				for(int i=0,len = parameters.size(); i < len; i++){
					Object v = parameters.getValue(i);
					if(v == null)
						continue;
					String value = v.toString();
					String key = parameters.get(i);
					multipartBuilder.addTextBody(key, value);
					
				}
			}
			entity = multipartBuilder.build();
		}else if(parameters != null && parameters.size() > 0){
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			for(int i=0,len = parameters.size(); i < len; i++){
				Object v = parameters.getValue(i);
				if(v == null)
					continue;
				String value = v.toString();
				String key = parameters.get(i);
				params.add(new BasicNameValuePair(key, value));
			}
			EntityBuilder builder = EntityBuilder.create();
			builder.setContentEncoding("UTF-8");
			builder.setParameters(params);
			entity = builder.build();
		}
		if(entity != null)
			httpPost.setEntity(entity);
		try {
			HttpResponse response = client.execute(httpPost);
			return EntityUtils.toString(response.getEntity(), "GBK");
		}finally{
			httpPost.abort();
		}
	}
	
	/**
	 * 通過POST方式向伺服器傳送資料
	 * @param url 地址
	 * @param parameters 引數集
	 * @param attachs 附件列表
	 * @return 返回結果
	 * @throws HttpException
	 * @throws IOException
	 */
	public static String httpPostUpload(String url,LinkedMap<String,Object> parameters,LinkedMap<String,File> attachs) throws HttpException, IOException{
		return httpPostUpload(createHttpClient(),url,parameters,attachs);
	}
	
	/**
	 * 建立httpClient物件
	 * @return httpClient物件
	 */
	public static HttpClient createHttpClient(){
		return HttpClientBuilder.create().build();
	}
	
	
	
	 /**
	  * 模擬瀏覽器post提交
	  * @param url
	  * @return
	  */
	 public static HttpPost getPostMethod(String url) {
	  HttpPost pmethod = new HttpPost(url); // 設定響應頭資訊
	  pmethod.addHeader("Connection", "keep-alive");
	  pmethod.addHeader("Accept", "*/*");
	  pmethod.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
	  pmethod.addHeader("Host", "mp.weixin.qq.com");
	  pmethod.addHeader("X-Requested-With", "XMLHttpRequest");
	  pmethod.addHeader("Cache-Control", "max-age=0");
	  pmethod.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
	  return pmethod;
	 }

	 /**
	  * 模擬瀏覽器GET提交
	  * @param url
	  * @return
	  */
	 public static HttpGet getGetMethod(String url) {
	  HttpGet pmethod = new HttpGet(url);
	  // 設定響應頭資訊
	  pmethod.addHeader("Connection", "keep-alive");
	  pmethod.addHeader("Cache-Control", "max-age=0");
	  pmethod.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
	  pmethod.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/;q=0.8");
	  return pmethod;
	 }
	 
	 /**
	  * get方式模擬瀏覽器請求
	  * @param url
	  * @return
	  */
	 public static String getHttpGetReturnStr(String url)
	 {
		 
		 HttpGet get = getGetMethod(url);
		 String returnStr=null;
		 try {
		  HttpResponse response = getHttpclient().execute(get);
		  returnStr = EntityUtils.toString(response.getEntity(), "utf-8");
		 } catch (Exception e) {
				logger.info("#################   HttpGet請求出錯");
	     }
		return returnStr;
	 }
	 
	 /**
	  * post模擬瀏覽器請求,
	  * @param url
	  * @param entityJson
	  * @return
	  */
	 public static String getHttpPostReturnStr(String url,String entityJson)
	 {
		 
		 HttpPost httpost = HttpClientConnectionManager.getPostMethod(url);
		 httpost.setEntity(new StringEntity(entityJson, "UTF-8"));
		 String returnStr=null;
          try {
		
		  HttpResponse response = getHttpclient().execute(httpost);
		  returnStr = EntityUtils.toString(response.getEntity(), "utf-8");
			
  		} catch (Exception e) {
  			logger.info("#################   HttpPost請求出錯");
  		}
		return returnStr;
	 }
	
}