1. 程式人生 > >http模擬登陸及發請求

http模擬登陸及發請求

jsession mps lan com md5 url nbsp lba ++

首先聲明下,如果服務端寫入的cookie屬性是HttpOnly的,程序是不能自動獲取cookie的,需要人工登陸網站獲取cookie再把cookie寫死,如下圖所示:

http測試工具:http://www.atool.org/httptest.php

技術分享圖片

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

}

  

http模擬登陸及發請求