常用的PostMethod及getMethod请求

在java开发中经常遇到各应用之间交互的情况,下面主要给出常用两种请求放式:
1、PostMethod请求

   public  void postMethod( Map<String,Object> paramMap){
        SimpleDateFormat df = new  SimpleDateFormat("yyyy-MM-dd");
		String cookie1=paramMap.get("cookie1").toString();
		String html = "null";	
		//组装报文
		JSONObject jsonObject = new JSONObject();
		JSONObject jsonObjectHead = new JSONObject();
		String tran_date = df.format(new Date().getTime()).toString();
		jsonObjectHead.put("tran_date", tran_date);//时间
		jsonObjectHead.put("id","001");
		jsonObject.put("transaction", jsonObjectHead);
		JSONObject jsonObjectBody = new JSONObject();		
		jsonObjectBody.put("name", "fank");//
		jsonObjectBody.put("age", "30");//
		jsonObject.put("data", jsonObjectBody);
		
		String requestJson = jsonObject.toString();		
		//构造httpclient实例并且忽略服务端SSL证书校验
		ProtocolSocketFactory fcty = new CertificateValidationIgnored();
		Protocol.registerProtocol("https", new Protocol("https", fcty, 443));
		HttpClient httpClient=new HttpClient();
		try {
	        //对请求报文进行加密
			requestJson = HttpEncryptUtil.appEncrypt(requestJson);
			String urlszrd = "https://www.baidu.com";//请求地址
			PostMethod postMethod = new PostMethod(urlszrd);
			//需要携带cookie时
			postMethod.setRequestHeader("cookie",cookie1);
			RequestEntity se = new StringRequestEntity (requestJson ,"application/json" ,"UTF-8");
			postMethod.setRequestEntity(se);
			postMethod.setRequestHeader("Content-Type","application/json");
			//默认的重试策略
			postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
			postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 50000);//设置超时时间
			try{
				//设置HttpClient接收Cookie
				httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
				int statusCode = httpClient.executeMethod(postMethod);
				BufferedReader reader = new BufferedReader(new InputStreamReader(postMethod.getResponseBodyAsStream()));
				StringBuffer stringBuffer = new StringBuffer();
				String str = "";
				while((str = reader.readLine())!=null){
					stringBuffer.append(str);
				}
				html=stringBuffer.toString();
			}catch(Exception e){
				e.printStackTrace();
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}

2、PostMethod请求2

	String url="https://xxxxxxxx";
		String retStr="";
		String cookie1="xxxxxx";
		try {
			NameValuePair[] data = {
					new NameValuePair("nsrsbh","91510xxxxx048422")
			};
			retStr = postMethod(url2,data,cookie1);
		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
public static String postMethod(String url,NameValuePair[] dataxypj,String cookie1){
	String html = "";
	//构造httpclient实例并且忽略服务端SSL证书校验
	ProtocolSocketFactory fcty = new CertificateValidationIgnored();
	Protocol.registerProtocol("https", new Protocol("https", fcty, 443));
	HttpClient httpClient=new HttpClient();

	//模拟登录,按实际服务器端要求选用Post 或 Get请求方式
	PostMethod postMethod = new PostMethod(url);
	//设置相同的cookie
	postMethod.setRequestHeader("cookie",cookie1);
	postMethod.setRequestHeader("User-Agent","Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Mobile Safari/537.36");
	postMethod.setRequestHeader("Content-Type","application/x-www-form-urlencoded");

	//设置登录时需要的信息
	postMethod.setRequestBody(dataxypj);

	try{
		int statusCode = httpClient.executeMethod(postMethod);
		html = postMethod.getResponseBodyAsString();

		if(statusCode == 200){
			Cookie[] cookies1 = httpClient.getState().getCookies();
			StringBuffer tmpcookies1 = new StringBuffer();
			for(Cookie c1 : cookies1) {
				tmpcookies1.append(c1.toString()+";");
				System.out.println("访问页面cookies : "+c1.toString());
				cookie1 = tmpcookies1.toString();
				//cookie1 = c1.toString();
			}
			System.out.println("接口调用成功!");
			System.out.println("接口调用返回报文:"+html);
		}
	}catch(Exception e){
		e.printStackTrace();
	}
	return html;

}

3.getMethod请求

public  void getMethod(Map<String,Object> mndlMap) throws Exception {
	String html = "null";
	//验证码下载网址
	String checkCodeURL = "https://www.baidu.com";
	//创建浏览器对象
	//HttpClient httpClient = new HttpClient();
	//构造httpclient实例并且忽略服务端SSL证书校验
	ProtocolSocketFactory fcty = new CertificateValidationIgnored();
	Protocol.registerProtocol("https", new Protocol("https", fcty, 443));
	HttpClient httpClient=new HttpClient();

	//先访问验证码页面,获取验证码
	GetMethod getMethod1 = new GetMethod(checkCodeURL);
	try {
		//设置HttpClient接收Cookie
		httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);

		httpClient.executeMethod(getMethod1);
		//获取访问后的Cookie
		Cookie[] cookies1 = httpClient.getState().getCookies();
		StringBuffer tmpcookies1 = new StringBuffer();
		for(Cookie c1 : cookies1) {
			tmpcookies1.append(c1.toString()+";");
			System.out.println("访问页面cookies : "+c1.toString());
			cookie1 = tmpcookies1.toString();
			//cookie1 = c1.toString();
		}

		//该处代码是用于验证码自动识别
		//txtSecretCode = ImagePreProcess.getAllOrc("D:\\java爬虫jar包\\verifycode\\vc.gif");
	}catch(Exception e) {
		e.printStackTrace();
	}
}	
  • 4
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值