java session代码_可以保持session的java代码片段

import java.io.File;

import java.io.IOException;

import java.util.*;

import org.apache.commons.collections.map.HashedMap;

import org.apache.commons.lang3.StringUtils;

import org.apache.http.*;

import org.apache.http.client.ClientProtocolException;

import org.apache.http.client.CookieStore;

import org.apache.http.client.HttpClient;

import org.apache.http.client.config.RequestConfig;

import org.apache.http.client.entity.UrlEncodedFormEntity;

import org.apache.http.client.methods.CloseableHttpResponse;

import org.apache.http.client.methods.HttpGet;

import org.apache.http.client.methods.HttpPost;

import org.apache.http.client.protocol.HttpClientContext;

import org.apache.http.cookie.Cookie;

import org.apache.http.entity.StringEntity;

import org.apache.http.entity.mime.HttpMultipartMode;

import org.apache.http.entity.mime.MultipartEntityBuilder;

import org.apache.http.entity.mime.content.FileBody;

import org.apache.http.impl.client.BasicCookieStore;

import org.apache.http.impl.client.CloseableHttpClient;

import org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy;

import org.apache.http.impl.client.DefaultRedirectStrategy;

import org.apache.http.impl.client.HttpClientBuilder;

import org.apache.http.impl.cookie.BasicClientCookie;

import org.apache.http.message.BasicNameValuePair;

import org.apache.http.util.CharsetUtils;

import org.apache.http.util.EntityUtils;

import org.apache.log4j.LogManager;

import org.apache.log4j.Logger;

import org.eclipse.jetty.util.ajax.JSON;

/**

* 保持同一session的HttpClient工具类

* @author zhangwenchao

*

*/

public class HttpClientKeepSession {

private static final Logger LOG = LogManager.getLogger(HttpClient.class);

public static CloseableHttpClient httpClient = null;

public static HttpClientContext context = null;

public static CookieStore cookieStore = null;

public static RequestConfig requestConfig = null;

static {

init();

}

private static void init() {

context = HttpClientContext.create();

cookieStore = new BasicCookieStore();

// 配置超时时间(连接服务端超时1秒,请求数据返回超时2秒)

requestConfig = RequestConfig.custom().setConnectTimeout(120000).setSocketTimeout(60000)

.setConnectionRequestTimeout(60000).build();

// 设置默认跳转以及存储cookie

httpClient = HttpClientBuilder.create()

.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy())

.setRedirectStrategy(new DefaultRedirectStrategy()).setDefaultRequestConfig(requestConfig)

.setDefaultCookieStore(cookieStore).build();

}

/**

* http get

*

* @param url

* @return response

* @throws ClientProtocolException

* @throws IOException

*/

public static String get(String url,Map params) throws Exception {

long responseLength = 0; //响应长度

String responseContent = null; //响应内容

CloseableHttpResponse response = null;

if(params != null){

Set keySet = params.keySet();

Iterator iterator = keySet.iterator();

String keyString = "";

String key = null;

while (iterator.hasNext()){

key = iterator.next();

if(keyString.length()>0){

keyString += "&";

}

keyString += key +"="+params.get(key);

}

if(url.indexOf("?") > 0 ){

url = url+"&"+keyString;

}else {

url = url+"?"+keyString;

}

}

HttpGet httpget = new HttpGet(url);

response = httpClient.execute(httpget, context);

cookieStore = context.getCookieStore();

List cookies = cookieStore.getCookies();

for (Cookie cookie : cookies) {

LOG.debug("key:" + cookie.getName() + " value:" + cookie.getValue());

}

//printResponse(response);

HttpEntity entity = null;

if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {

entity = response.getEntity(); //获取响应实体

if(null != entity){

responseContent = EntityUtils.toString(entity, "UTF-8");

EntityUtils.consume(entity); //Consume response content

}

}else{

String param= null;

if(params != null){

param = JSON.toString(params);

}

// LOG.error("url="+url+"\r\n param="+param+"\r\n statecode="+response.getStatusLine().getStatusCode());

String errorMsg = "url="+url+"\r\n param="+param+"\r\n statecode="+response.getStatusLine().getStatusCode();

LOG.error(errorMsg);

throw new Exception(errorMsg);

}

return responseContent;

}

/**

* http post

*

* @param url

* @param params

* form表单

* @return response

* @throws ClientProtocolException

* @throws IOException

*/

public static String post(String url, Map params)

throws Exception {

CloseableHttpResponse response = null;

String responseContent = null; //响应内容

HttpPost httpPost = new HttpPost(url);

List nvps = new ArrayList();

if(params != null){

Set keySet = params.keySet();

Iterator iterator = keySet.iterator();

String key = null;

while (iterator.hasNext()){

key = iterator.next();

nvps.add(new BasicNameValuePair(key, params.get(key).toString()));

}

}

httpPost.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));

response = httpClient.execute(httpPost, context);

cookieStore = context.getCookieStore();

List cookies = cookieStore.getCookies();

// for (Cookie cookie : cookies) {

// LOG.debug("key:" + cookie.getName() + " value:" + cookie.getValue());

// }

// printResponse(response);

HttpEntity entity = null;

if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {

entity = response.getEntity(); //获取响应实体

if(null != entity){

responseContent = EntityUtils.toString(entity, "UTF-8");

EntityUtils.consume(entity); //Consume response content

}

}else{

String param= null;

if(params != null){

param = JSON.toString(params);

}

String errorMsg = "url="+url+"\r\n param="+param+"\r\n statecode="+response.getStatusLine().getStatusCode();

LOG.error(errorMsg);

throw new Exception(errorMsg);

}

return responseContent;

}

public static String sendPostByJson(String url, String body) throws Exception {

CloseableHttpResponse response = null;

String responseContent = null; //响应内容

HttpPost httpPost = new HttpPost(url);

if(StringUtils.isNotEmpty(body)){

HttpEntity entity2 = new StringEntity(body, Consts.UTF_8);

httpPost.setEntity(entity2);

}

response = httpClient.execute(httpPost, context);

cookieStore = context.getCookieStore();

// List cookies = cookieStore.getCookies();

// for (Cookie cookie : cookies) {

// LOG.debug("key:" + cookie.getName() + " value:" + cookie.getValue());

// }

// printResponse(response);

HttpEntity entity = null;

if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {

entity = response.getEntity(); //获取响应实体

if(null != entity){

responseContent = EntityUtils.toString(entity, "UTF-8");

EntityUtils.consume(entity); //Consume response content

}

}else{

String errorMsg = "url="+url+"\r\n param="+body+"\r\n statecode="+response.getStatusLine().getStatusCode();

LOG.error(errorMsg);

throw new Exception(errorMsg);

}

return responseContent;

}

public static void upload(String url) {

try {

HttpPost httppost = new HttpPost(url);

FileBody bin = new FileBody(new File("C:\\Users\\zhangwenchao\\Desktop\\jinzhongzi.jpg"));

HttpEntity reqEntity = MultipartEntityBuilder.create()

.setMode(HttpMultipartMode.BROWSER_COMPATIBLE)

.addPart("uploadFile", bin)

.setCharset(CharsetUtils.get("UTF-8")).build();

httppost.setEntity(reqEntity);

System.out.println("executing request: "+ httppost.getRequestLine());

CloseableHttpResponse response = httpClient.execute(httppost,context);

try {

cookieStore = context.getCookieStore();

List cookies = cookieStore.getCookies();

for (Cookie cookie : cookies) {

LOG.debug("key:" + cookie.getName() + " value:" + cookie.getValue());

}

System.out.println("----------------------------------------");

System.out.println(response.getStatusLine());

HttpEntity resEntity = response.getEntity();

if (resEntity != null) {

// 响应长度

System.out.println("Response content length: "

+ resEntity.getContentLength());

// 打印响应内容

System.out.println("Response content: "

+ EntityUtils.toString(resEntity));

}

// 销毁

EntityUtils.consume(resEntity);

} finally {

response.close();

}

} catch (ClientProtocolException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

}

/**

* 手动增加cookie

* @param name

* @param value

* @param domain

* @param path

*/

public static void addCookie(String name, String value, String domain, String path) {

BasicClientCookie cookie = new BasicClientCookie(name, value);

cookie.setDomain(domain);

cookie.setPath(path);

cookieStore.addCookie(cookie);

}

/**

* 把当前cookie从控制台输出出来

*

*/

public static void printCookies() {

LOG.info("headers:");

cookieStore = context.getCookieStore();

List cookies = cookieStore.getCookies();

for (Cookie cookie : cookies) {

LOG.info("key:" + cookie.getName() + " value:" + cookie.getValue());

}

}

/**

* 检查cookie的键值是否包含传参

*

* @param key

* @return

*/

public static boolean checkCookie(String key) {

cookieStore = context.getCookieStore();

List cookies = cookieStore.getCookies();

boolean res = false;

for (Cookie cookie : cookies) {

if (cookie.getName().equals(key)) {

res = true;

break;

}

}

return res;

}

public static void main(String[] args) throws Exception {

//用户登陆

Map loginParam = new HashedMap();

loginParam.put("loginId","baoyong");

loginParam.put("passwd","qqq111");

String response = HttpClientKeepSession.post(

"http://127.0.0.1:8080/xyre/enterpriseAdmin/dologin",

loginParam);

LOG.info(response);

// printResponse(response);

printCookies();

Map indexParam = new HashedMap();

response = HttpClientKeepSession.post(

"http://127.0.0.1:8080/xyre/enterpriseAdmin/get",

loginParam);

LOG.info(response);

//上传数据

// HttpClientKeepSession.upload("http://localhost:8080/BCP/all/test/upload");

// printCookies();

System.exit(0);

}

}

终于可以做session登录验证了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值