java后台获取session_JAVA程序通过后台登陆网站,获取Session,然后再POST Http Request添加数据到...

这个Java程序演示了如何通过后台模拟登录网站并获取Session。它使用HttpClient库执行HTTP请求,包括GET和POST方法,处理Cookie以维持会话状态,并进行参数解析。程序适用于执行自动化任务或集成测试,例如在需要登录的场景下添加数据。
摘要由CSDN通过智能技术生成

package cn.javadr.product;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.io.OutputStream;

import java.net.HttpURLConnection;

import java.net.MalformedURLException;

import java.net.URL;

import java.net.URLConnection;

import java.util.HashMap;

import java.util.Iterator;

import java.util.Map;

import java.util.Map.Entry;

/**

* HttpClient

*

* @author Tang Ren email:

* href="mailto:tangren1206@163.com">tangren1206@163.com

*

* post@@http://www.51etest.com/dede/login.php@@userid=xxxx&pwd=xxxxxx&gotopage=/dede/&dopost=login

*

* post@@http://www.51etest.com/dede/ad_add.php@@dopost=save&tagname=test&typeid=0&adname=test&starttime=2008-05-29

* 20:58:25&endtime=2008-06-28 20:58:25×et=0&normbody=test&expbody=test

*

*/

/**

*

*/

public class HttpClient {

private static final String USER_AGENT_VALUE = "Mozilla/4.0 (compatible; MSIE 6.0; Windows XP)";

/**

* Cmd splitor default is symbol '$$'.

*/

private static final String HTTP_CLIENT_CMD_SPLITOR = "@@";

/**

* Post parameter splitor default is symbol '&'.

*/

private static final String POST_PARAMETER_SPLITOR = "&";

private static final String POST_PARAMETER_KV_SPLITOR = "=";

private String cookie = null;

private Map cookieMap = new HashMap();

public static void main(String[] args) {

HttpClient client = new HttpClient();

}

public HttpClient() {

// Input http request url

BufferedReader consleReader = new BufferedReader(new InputStreamReader(

System.in));

String httpResponse = null;

String url = null;

String cmd = null;

String method = null;

try {

while (true) {

cmd = consleReader.readLine();

if (cmd.indexOf(HTTP_CLIENT_CMD_SPLITOR) == -1)

continue;

method = cmd.split(HTTP_CLIENT_CMD_SPLITOR)[0];

url = cmd.split(HTTP_CLIENT_CMD_SPLITOR)[1];

if (method.toUpperCase().equals("GET")) {

httpResponse = this.getMethod(url, true);

} else if (method.toUpperCase().equals("POST")) {

Map parameters = this.parsePostParameters(cmd

.split(HTTP_CLIENT_CMD_SPLITOR)[2]);

httpResponse = this.postMethod(url, parameters, true);

}

System.out.println(httpResponse);

}

} catch (IOException e) {

e.printStackTrace();

} finally {

try {

consleReader.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

/**

* Request specifid url with 'GET' method. And return HTTP response content.

*

* @param url

* @return

*/

private String getMethod(String url, boolean keepCookie) {

if (url == null || url.length() == 0) {

return "Requst url could not be null or empty.";

}

StringBuffer result = new StringBuffer();

try {

HttpURLConnection httpURLConnection = this.getHttpURLConnection(

url, keepCookie);

// Set request properties.

this.settingHttpRequestHeader(httpURLConnection);

httpURLConnection.setRequestMethod("GET");

// Getting or setting cookie

this.gettingOrSettingCookie(httpURLConnection, keepCookie);

InputStream httpInputStream = httpURLConnection.getInputStream();

BufferedReader httpBufferedReader = new BufferedReader(

new InputStreamReader(httpInputStream, "GBK"));

result.append(this.readBufferedContent(httpBufferedReader));

// Connect to host.

httpURLConnection.connect();

} catch (IOException e) {

e.printStackTrace();

return "getHttpURLConnection failed.";

}

return result.toString();

}

public String postMethod(String url, Map parameters, boolean keepCookie) {

StringBuffer httpResponse = new StringBuffer();

HttpURLConnection httpURLConnection = null;

OutputStream httpOutputStream = null;

try {

httpURLConnection = this.getHttpURLConnection(url, keepCookie);

// Set request properties.

this.settingHttpRequestHeader(httpURLConnection);

// Set request method with 'POST'

httpURLConnection.setRequestMethod("POST");

// Set connection output is true.

httpURLConnection.setDoOutput(true);

// Getting or setting cookie

this.gettingOrSettingCookie(httpURLConnection, keepCookie);

// Get Http output stream

httpOutputStream = httpURLConnection.getOutputStream();

// Build post parameters string

StringBuffer postParams = new StringBuffer();

int index = 0;

for (Iterator iter = parameters.entrySet().iterator(); iter

.hasNext(); index++) {

Entry entry = iter.next();

postParams.append(index != 0 ? "&" : "");

postParams.append(entry.getKey());

postParams.append("=");

postParams.append(entry.getValue());

}

httpOutputStream.write(postParams.toString().getBytes());

BufferedReader httpBufferedReader = new BufferedReader(

new InputStreamReader(httpURLConnection.getInputStream()));

httpResponse.append(this.readBufferedContent(httpBufferedReader));

} catch (IOException e) {

e.printStackTrace();

return null;

} finally {

try {

httpOutputStream.close();

} catch (IOException e) {

e.printStackTrace();

}

}

return httpResponse.toString();

}

/**

* Setting HTTP request header properties

*

* @param httpURLConnection

*/

private void settingHttpRequestHeader(HttpURLConnection httpURLConnection) {

if (httpURLConnection == null)

return;

httpURLConnection.setRequestProperty("User-Agent", USER_AGENT_VALUE);

// TODO setting some other properties here . . .

}

/**

* Get HttpURLConnection by specified url string.

*

* @param url

* @return

* @throws IOException

*/

private HttpURLConnection getHttpURLConnection(String url,

boolean keepCookie) throws IOException {

URL urlObj = new URL(url);

URLConnection urlConnection = urlObj.openConnection();

if (urlConnection instanceof HttpURLConnection)

return (HttpURLConnection) urlConnection;

throw new MalformedURLException();

}

/**

* Read bufferedReader buffered content.

*

* @param bufferedReader

* @return

*/

private String readBufferedContent(BufferedReader bufferedReader) {

if (bufferedReader == null)

return null;

StringBuffer result = new StringBuffer();

String line = null;

try {

while ((line = bufferedReader.readLine()) != null) {

result.append(line);

}

} catch (IOException e) {

e.printStackTrace();

return null;

}

return result.toString();

}

/**

* Parse and create parameter map with parameter string

*

* @param parameterString

* @return

*/

private Map parsePostParameters(String parameterString) {

if (parameterString == null || parameterString.length() == 0)

return null;

Map result = new HashMap();

// only one parameter key-value pair

if (parameterString.indexOf(POST_PARAMETER_SPLITOR) == -1) {

if (parameterString.indexOf(POST_PARAMETER_KV_SPLITOR) != -1)

result.put(parameterString.split(POST_PARAMETER_KV_SPLITOR)[0],

parameterString.split(POST_PARAMETER_KV_SPLITOR)[1]);

} else {

String[] keyValues = parameterString.split(POST_PARAMETER_SPLITOR);

for (int i = 0; i < keyValues.length; i++) {

String keyValue = keyValues[i];

result.put(keyValue.split(POST_PARAMETER_KV_SPLITOR)[0],

keyValue.split(POST_PARAMETER_KV_SPLITOR)[1]);

}

}

return result;

}

/**

* Get or set cookie.

*

* @param httpURLConnection

* @param keepCookie

*/

private void gettingOrSettingCookie(HttpURLConnection httpURLConnection,

boolean keepCookie) {

// Getting or setting cookie.

if (cookie == null || cookie.length() == 0) {

String setCookie = httpURLConnection.getHeaderField("Set-Cookie");

cookie = setCookie.substring(0, setCookie.indexOf(";"));

} else if (keepCookie) {

httpURLConnection.setRequestProperty("Cookie", cookie);

}

}

}

分享到:

18e900b8666ce6f233d25ec02f95ee59.png

72dd548719f0ace4d5f9bca64e1d7715.png

2011-04-12 17:28

浏览 11167

评论

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
package test; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import java.util.List; import java.util.Map; public class HttpTest { private HttpURLConnection hc = null; private static final String oneUrlString = "http://xxx.jsp"; private static final String twoUrlString = "http://xxx.action"; public String getSessionId() { String sessionId = ""; try { URL url = new URL(oneUrlString); hc = (HttpURLConnection) url.openConnection();//默认的用GET提交 hc.setDoOutput(true); hc.connect(); Map map = hc.getHeaderFields(); //得到Cookie的所有内容,包括SESSIONID,在进行下次提交的时候 直接把这个Cookie的值设到头里头就行了 //淡然只得到SESSIONID也很简单的 ,但是有时候Set-Cookie的值有几个的 List list = (List) map.get("Set-Cookie"); if(list.size() == 0||list == null) { return null; } StringBuilder builder = new StringBuilder(); for(String str : list) { sessionId = builder.append(str).toString(); } hc.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return sessionId; } public String getResponseContext(String parameters) { String responseContext = ""; try { URL url = new URL(twoUrlString); hc = (HttpURLConnection) url.openConnection();//使用POST提交 hc.addRequestProperty("Cookie", getSessionId()); hc.setDoOutput(true); hc.connect(); OutputStream out = hc.getOutputStream(); //参数是a=""&b=""这样拼接的一个串 out.flush(); out.close(); out.write(parameters.getBytes(),0,parameters.getBytes().length); InputStream in = hc.getInputStream(); InputStreamReader reader = new InputStreamReader(in,"gb2312"); BufferedReader read = new BufferedReader(reader); StringBuilder builder = new StringBuilder(); String str = ""; while((str = read.readLine()) != null) { builder = builder.append(str); } read.close(); reader.close(); in.close(); hc.disconnect(); responseContext = builder.toString(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return responseContext; } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值