可以保持session的java代码片段 博客分类: java
程序员文章站
2024-03-13 21:46:46
...
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<String,Object> params) throws Exception { long responseLength = 0; //响应长度 String responseContent = null; //响应内容 CloseableHttpResponse response = null; if(params != null){ Set<String> keySet = params.keySet(); Iterator<String> 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<Cookie> 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<String,String> params) throws Exception { CloseableHttpResponse response = null; String responseContent = null; //响应内容 HttpPost httpPost = new HttpPost(url); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); if(params != null){ Set<String> keySet = params.keySet(); Iterator<String> 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<Cookie> 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<Cookie> 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<Cookie> 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<Cookie> 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<Cookie> 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<String,String> 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<String,String> 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登录验证了。
推荐阅读
-
可以保持session的java代码片段 博客分类: java
-
控件位置可以配置的Swing桌面 博客分类: Java2D SwingWordPressSpringXMLF#
-
java读取纯真IP数据库QQwry.dat的源代码 博客分类: Java Java数据结构.netCacheJ#
-
java读取纯真IP数据库QQwry.dat的源代码 博客分类: Java Java数据结构.netCacheJ#
-
从源代码到Runtime发生的重排序 博客分类: java操作系统jvm 重排序编译器处理器重排序缓存一致性内存屏障
-
[SHELL]用于快速搜索C++/C/JAVA/汇编等源代码的SHELL脚本 博客分类: linux_app
-
java String类的操作 博客分类: 代码 java string
-
分布式环境中三种Session管理方法的使用场景及优缺点 . 博客分类: java基础
-
使用maven 如何生成源代码的jar包 博客分类: Java WebJava maven打包源码打包源代码sourcejarsources.jar
-
hadoop客户端提交job的java代码 博客分类: java