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登录验证了。
相关推荐
用户只需运行这个文件,输入或导入多行SQL,然后工具会生成对应的Java代码片段,用户可以直接复制粘贴到自己的Java项目中。 在实际使用中,这个工具可能具备以下特性: 1. 支持SQL语法高亮和格式化,使生成的Java...
下面是一个简单的使用Jedis实现分布式Session的Java代码片段: ```java import redis.clients.jedis.Jedis; public class SessionStore { private Jedis jedis; public SessionStore() { // 初始化Jedis连接 ...
在WebSphere Studio V5.1.2中使用代码片段进行EJB编程,是Java企业级应用开发中的一个重要环节。WebSphere Studio是IBM提供的一款集成开发环境(IDE),它支持多种Java应用程序的开发,包括EJB(Enterprise ...
这个"Java爬虫代码示例"压缩包很可能是包含了一些基本的爬虫代码片段,涵盖了以上所述的部分或全部知识点。初学者可以通过阅读和运行这些示例,逐步理解并掌握Java爬虫的实现过程。在实际项目中,还需要不断学习和...
1. Spring框架:可能包含Bean配置、自动装配、AOP示例,以及Spring MVC的控制器、服务、模型和视图的代码片段。 2. Struts框架:可能涵盖Action类、Struts配置文件、JSP视图的创建和业务逻辑处理等。 3. Hibernate...
JSP(JavaServer Pages)则是一种视图技术,方便在HTML中嵌入Java代码。Servlet和JSP通常配合使用,实现MVC(Model-View-Controller)架构,其中Servlet负责业务逻辑处理,JSP负责展示数据。 2. **Filter与Listener...
JSP是由静态HTML模板和Java代码片段组成的。HTML用于构建页面结构,而Java代码则负责处理动态内容。JSP页面会被Web容器(如Tomcat)转换成Servlet,然后执行。JSP的元素包括指令(Directives)、脚本元素...
5. **示例代码片段**: ```java Properties props = new Properties(); props.put("mail.smtp.auth", "true"); props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", "smtp.example....
JSP文件(`.jsp`)则可能负责展示用户界面,它们可以包含HTML、CSS和Java脚本片段,这些脚本片段在服务器端执行并生成HTML响应。 2. **Model-View-Controller (MVC)**:为了组织代码,项目可能会遵循MVC设计模式。...
JSP页面中的Java代码片段被包含在特殊的标记中,如和 %>。JSP的生命周期包括三个阶段:加载和实例化JSP页面,处理请求并执行JSP页面中的Java代码,然后编译生成Servlet,并且如果有必要的话,服务请求。 在JSP页面...
在同一个 `GroovyShell` 实例中,所有变量值都会保留在一个“session”中,这意味着你在后续的 `evaluate` 调用中可以继续访问和修改这些变量。 例如,以下代码展示了如何在 GroovyShell 中调用方法: ```java ...
"Tomcat与Java.Web开发技术详解源代码"这个压缩包很可能包含了示例项目、Tomcat配置文件以及讲解这些概念的代码片段。通过深入研究这些源代码,开发者可以更好地理解Tomcat的工作方式,学习如何配置和优化服务器,...
根据给定的部分内容,我们可以看到一个简单的Java示例代码片段,该片段展示了如何在Java Web应用中获取SessionID: ```java HttpSession hs = request.getSession(); // 获取Session String id = Integer....
#### Java代码片段编写 - **核心知识点**:包括控制流程、文件操作和网络请求等。例如,判断用户是否登录、获取URL参数、删除文件等。 - **应用场景**:在Web应用中判断用户状态、处理URL请求参数、进行文件系统操作...
- 避免在JSP中写大量Java代码,保持页面清晰,将业务逻辑移至后台或JavaBeans。 - 使用EL和JSTL减少脚本片段,提高可读性。 - 使用MVC模式分离关注点,使代码更易于维护。 通过这21个小例子,开发者可以深入理解...
从提供的代码片段来看,这段代码主要涉及了如何在Java环境下实现购物车的基本功能,尤其针对的是如何处理用户选择的商品,并将这些信息存储在session中以备后续使用。 ### 一、Session和Vector的作用 在Java Web...
- 互动直播:观众可以控制直播流,如慢放、回放特定片段。 6. **学习与调试**: - 熟悉RTSP协议规范,理解每个命令和响应的含义。 - 使用Wireshark等网络嗅探工具,查看网络交互过程,帮助调试代码。 - 设置...
3. **代码示例**:提供创建和控制RTSP会话的Java代码片段。 4. **异常处理**:处理可能出现的网络错误、解码问题等。 5. **性能优化**:如何减少延迟,提高播放质量。 6. **实际应用**:可能包含如何将RTSP客户端...
1. **JSP基本结构**:JSP文件本质上是HTML文件,可以在其中添加Java代码片段(Scriptlets)、表达式(Expressions)和声明(Declarations)。这些元素被JSP引擎转换为Servlet代码执行。 2. **JSP指令**:包括`page`...
JNI允许Java代码调用本地(C/C++)代码,从而可以利用操作系统提供的API来访问硬件资源。然而,对于扫描仪这样的设备,直接使用JNI可能过于复杂且不切实际。因此,通常我们会寻找已经存在的库,如Twain_32或者WIA...