`

java 模拟微信浏览器http请求

阅读更多
	
public static void main(String[] args) {
			

			   */
			   String url="http://xxxx/park/search";
			   List<NameValuePair> params  = new ArrayList<NameValuePair>();
			   
			
			   params.add(new BasicNameValuePair("centerLon", "xx"));
			   params.add(new BasicNameValuePair("centerLat", "xx"));
			   params.add(new BasicNameValuePair("carNo", "xx"));
			   
			   StatusBean sb = post(url,params);
			   System.out.println("xxx"+sb.toString());
			
		
		}

/** 超时设置 */
		private static final int connectTimeOut = 3000;
		private static final int socketTimeOut = 3000;
     
    	 public static StatusBean<?> post(String url, List<NameValuePair> params) {
    			StatusBean<?> sb = null;
    			CloseableHttpClient httpclient = HttpClients.createDefault();
    			HttpPost httppost = new HttpPost(url);
    		    //在这里我们给Post请求的头部加上User-Agent来伪装成微信内置浏览器
    		    httppost.setHeader("User-Agent","Mozilla/5.0 (Linux; U; Android 2.3.6; zh-cn; GT-S5660 Build/GINGERBREAD) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1 MicroMessenger/4.5.255");
    		    //这个是在网上看到的,要加上这个,避免其他错误
    		    httppost.setHeader("Referer", "https://mp.weixin.qq.com");
    		    
    			CloseableHttpResponse response = null;
    			RequestConfig config;// 设置连接超时时间 设置数据传输超时时间
    			config= RequestConfig.custom().setConnectTimeout(connectTimeOut).setSocketTimeout(socketTimeOut).build();
    			httppost.setConfig(config);
    			HttpEntity reqEntity = null;
    			try {
    				if(null!=params && !params.isEmpty())reqEntity = new UrlEncodedFormEntity(params, "UTF-8");
    				httppost.setEntity(reqEntity);
    				response = httpclient.execute(httppost);
    				HttpEntity resEntity = response.getEntity();
    				if (resEntity != null) {
    					String entityStr = EntityUtils.toString(resEntity, "UTF-8");
    					System.out.println(entityStr);
    					sb = new StatusBean<>(true, "0000","通信成功!", null == entityStr ? "" : entityStr );
    				} else {
    					sb = new StatusBean<>(false, "9000","服务器无返回内容!", "");
    				}
    				
    			} catch (Exception e) {
    				sb = new StatusBean<>(false, "9999","请求服务器异常!", e.getMessage() + "--" + e);
    			} finally {
    				try { if(null!=response) response.close(); } catch (IOException e) {}// 关闭服务器请求接收
    				try { if(null!=httpclient) httpclient.close(); } catch (IOException e) {} // 关闭连接
    				response = null;
    				httpclient = null;
    				reqEntity = null;
    				httppost = null;
    				params = null;
    			}
    			return sb;
    		}
    	 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics