在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();
}
}