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.hl

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;
	 }
	
}


目录
相关文章
|
16天前
|
Java
java原生发送http请求
java原生发送http请求
|
1月前
|
Web App开发 Java 测试技术
《手把手教你》系列基础篇之(四)-java+ selenium自动化测试- 启动三大浏览器(下)基于Maven(详细教程)
【2月更文挑战第13天】《手把手教你》系列基础篇之(四)-java+ selenium自动化测试- 启动三大浏览器(下)基于Maven(详细教程) 上一篇文章,宏哥已经在搭建的java项目环境中实践了,今天就在基于maven项目的环境中给小伙伴们 或者童鞋们演示一下。
66 1
|
1月前
|
Web App开发 Java 测试技术
《手把手教你》系列基础篇之(三)-java+ selenium自动化测试- 启动三大浏览器(上)(详细教程)
【2月更文挑战第12天】《手把手教你》系列基础篇之(三)-java+ selenium自动化测试- 启动三大浏览器(上)(详细教程) 前边宏哥已经将环境搭建好了,今天就在Java项目搭建环境中简单地实践一下: 启动三大浏览器。按市场份额来说,全球前三大浏览器是:IE.Firefox.Chrome。因此宏哥这里主要介绍一下如何启动这三大浏览器即可,其他浏览器类似的方法,照猫画虎就可以了。
44 1
|
8天前
|
网络协议 Java API
深度剖析:Java网络编程中的TCP/IP与HTTP协议实践
【4月更文挑战第17天】Java网络编程重在TCP/IP和HTTP协议的应用。TCP提供可靠数据传输,通过Socket和ServerSocket实现;HTTP用于Web服务,常借助HttpURLConnection或Apache HttpClient。两者结合,构成网络服务基础。Java有多种高级API和框架(如Netty、Spring Boot)简化开发,助力高效、高并发的网络通信。
|
8天前
|
Java 测试技术 定位技术
《手把手教你》系列技巧篇(二十三)-java+ selenium自动化测试-webdriver处理浏览器多窗口切换下卷(详细教程)
【4月更文挑战第15天】本文介绍了如何使用Selenium进行浏览器窗口切换以操作不同页面元素。首先,获取浏览器窗口句柄有两种方法:获取所有窗口句柄的集合和获取当前窗口句柄。然后,通过`switchTo().window()`方法切换到目标窗口句柄。在项目实战部分,给出了一个示例,展示了在百度首页、新闻页面和地图页面之间切换并输入文字的操作。最后,文章还探讨了在某些情况下可能出现的问题,并提供了一个简单的本地HTML页面示例来演示窗口切换的正确操作。
36 0
|
8天前
|
安全 网络安全 开发工具
对象存储oss使用问题之flutter使用http库进行post请求文件上传返回400如何解决
《对象存储OSS操作报错合集》精选了用户在使用阿里云对象存储服务(OSS)过程中出现的各种常见及疑难报错情况,包括但不限于权限问题、上传下载异常、Bucket配置错误、网络连接问题、跨域资源共享(CORS)设定错误、数据一致性问题以及API调用失败等场景。为用户降低故障排查时间,确保OSS服务的稳定运行与高效利用。
31 1
|
22天前
|
Go
go语言的http post推送
go语言的http post推送
10 1
|
1月前
|
数据采集 缓存 前端开发
http和https请求服务器的时候在请求头部分都带什么到服务器呢?
HTTP和HTTPS请求头基本结构相似,HTTPS多了一层SSL/TLS加密。常见请求头如Accept(指定内容类型)、Authorization(身份验证)、Cookie(会话跟踪)、User-Agent(标识用户代理)等。HTTPS特有的头包括Upgrade-Insecure-Requests(升级到HTTPS)、Strict-Transport-Security(强制使用HTTPS)、Sec-Fetch-*(安全策略)和X-Content-Type-Options、X-Frame-Options等(增强安全性)。实际应用中,请求头会根据需求和安全策略变化。
20 0
|
1月前
|
缓存
HTTP协议中,GET和POST有什么区别?分别适用什么场景?
HTTP协议中,GET和POST有什么区别?分别适用什么场景?
36 0