http模拟登陆及发请求

时间:2023-11-17 23:14:56

首先声明下,如果服务端写入的cookie属性是HttpOnly的,程序是不能自动获取cookie的,需要人工登陆网站获取cookie再把cookie写死,如下图所示:

http测试工具:http://www.atool.org/httptest.php

http模拟登陆及发请求

package com.eshore.ismp.hbinterface.vsop.client.productCancelBatcher;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException; import com.alibaba.fastjson.JSONObject; public class HttpLoginUtils {
private final static String UTF8="UTF8";
private final static String MD5="MD5";
private final static char HEX_DIGITS[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd','e', 'f' };
private String cookie="JSESSIONID=E1487B3796D918D418DD8D184278C37E; LBN=node20; login_userId=24%2Cadmin_0%2C%E7%AE%A1%E7%90%86%E5%91%98; login_userType=1";
private static final String userName="admin_0";
private static final String password="Ismp!@#$";
public static final String type="1";
public static final String inputCode="JUGG";
public static final String oldCode="JUGG";
public static final String LOGIN_DCN_URL="http://127.0.0.1:30082/adminweb/user_login.do?";
public static final String LOGIN_URL="http://127.0.0.1:9000/adminweb/user_login.do?";
private static final String CANCEL_URL="http://127.0.0.1:9001/adminweb/hbmonth/productCancel.do?"; public void request(String tel,long time,String contentId) throws MalformedURLException,IOException{
/*try{
cookie=this.login();
}catch(Exception e){
e.printStackTrace();
}*/
//发送请求
JSONObject productList = new JSONObject();
productList.put("contentId",contentId+"@"+contentId);
productList.put("startTime", time);
productList.put("tel", tel);
String param = "productList=["+productList+"]&source=12"
+"&operatorAccount=admin_0"+"&operatorName=管理员";
URL url = new URL(CANCEL_URL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
httpConn.setDoOutput(true);
httpConn.setRequestMethod("POST");
httpConn.setUseCaches(false);
System.out.println("cookies:"+cookie);
httpConn.setRequestProperty("Cookie",cookie);
OutputStream output = httpConn.getOutputStream();
output.write(param.getBytes());
OutputStreamWriter outr = new OutputStreamWriter(output,"UTF-8");
outr.flush();
outr.close();
BufferedReader redoReader = new BufferedReader(new InputStreamReader(httpConn
.getInputStream(),"UTF-8"));
StringBuffer redoBuf = new StringBuffer();
String line = null;
while ((line = redoReader.readLine()) != null) {
redoBuf.append(line);
}
System.out.println("result info:"+redoBuf.toString());
}
/**
* @return
* 获取cookie
* @throws MalformedURLException,IOException
*/
public String login() throws MalformedURLException,IOException{
String cookie="";
String pswd = this.MD5Encode(password);
String param = "&username="+userName+"&password="+pswd+"&type="+type+"&inputCode="+inputCode+"&oldCode="+oldCode;
URL url=new URL(LOGIN_URL);
HttpURLConnection httpConn=(HttpURLConnection) url.openConnection();
//设定传送的内容类型是可序列化的java对象 (如果不设此项,在传送序列化对象时,当WEB服务默认的不是这种类型时可能抛java.io.EOFException)
httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
//设置是否从httpUrlConnection读入,默认情况下是true
httpConn.setDoOutput(true);
httpConn.setRequestMethod("POST");
//Post 请求不能使用缓存
httpConn.setUseCaches(false);
httpConn.setInstanceFollowRedirects(false);
//httpConn.connect();
// httpConn.getOutputStream();隐形调用了httpConn.connect();
OutputStream output = httpConn.getOutputStream();
//写入输出流
output.write(param.getBytes());
OutputStreamWriter outr = new OutputStreamWriter(output,"UTF-8");
outr.flush();
outr.close();
//创建读对象
BufferedReader loginReader = new BufferedReader(new InputStreamReader(httpConn
.getInputStream(),"UTF-8"));
StringBuffer sb = new StringBuffer();
String line = null;
//一行一行读取
while ((line = loginReader.readLine()) != null) {
sb.append(line);
}
System.out.println("output :"+sb.toString());
//获取服务端返回的cookie
cookie = httpConn.getHeaderField("Set-Cookie");
return cookie;
}
public String MD5Encode(String originalString) {
try {
byte[] originalBytes = originalString.getBytes(UTF8);
MessageDigest md = MessageDigest.getInstance(MD5);
md.update(originalBytes);
byte[] temps = md.digest();
int j = temps.length;
char[] str = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte tempByte = temps[i];
str[k++] = HEX_DIGITS[tempByte >>> 4 & 0xf];
str[k++] = HEX_DIGITS[tempByte & 0xf];
}
return new String(str).toUpperCase(); } catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}
/**
* @param args
* test
* @throws IOException
* @throws MalformedURLException
*/
public static void main(String[] args) throws MalformedURLException, IOException {
String cookie=new HttpLoginUtils().login();
System.out.println("cookie:"+cookie);
} }