HttpClient模仿登陆并维持同一session请求
核心思路是:
1.先从服务器获取到一个JSessionId,并把这个jsessionId存储下来 这很重要!! 一定要是从服务器获取
2.后面每请求一次都要把这个jsessionId放入到请求的cookies中,或者拼接在url后面:?jsessionId=xxxx
上代码:
/** * * @param postType 0:get,1:post, 2:put, 3:delete * @param url * @param contentType {@link org.apache.http.entity.ContentType contentType} * @param headers 请求头参数集合 * @param clientCookies 包含的cookie * @param jsonObject 请求参数 * @return */ public static CloseableHttpResponse httpClient(String postType, String url, ContentType contentType, Map<String,String> headers, List<BasicClientCookie> clientCookies, JSONObject jsonObject) { CloseableHttpClient httpClient = HttpClients.createDefault(); if(clientCookies != null && !clientCookies.isEmpty()) { BasicCookieStore cookieStore = new BasicCookieStore(); cookieStore.addCookies(clientCookies.toArray(new Cookie[]{})); httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build(); } CloseableHttpResponse httpResponse = null; HttpEntity entity = null; try { if ("0".equals(postType)) { //===== get =====// URIBuilder uriBuilder = new URIBuilder(url); // 设置参数 if(jsonObject != null && !jsonObject.isEmpty()) { List<NameValuePair> list = new LinkedList<>(); for (Map.Entry<String,?> entry : jsonObject.entrySet()) { list.add(new BasicNameValuePair(entry.getKey(), jsonObject.getString(entry.getKey()))); } uriBuilder.addParameters(list); } HttpGet httpGet = new HttpGet(uriBuilder.build()); httpGet.setProtocolVersion(HttpVersion.HTTP_1_0); //设置header setHttpClientHeaders(contentType, headers, httpGet); //发送请求 httpResponse = httpClient.execute(httpGet); } else if("1".equals(postType)) { //===== post =====// HttpPost httpPost = new HttpPost(url); // httpPost.setProtocolVersion(HttpVersion.HTTP_1_0); // 设置请求头 setHttpClientHeaders(contentType, headers, httpPost); //增加参数 if(contentType == ContentType.APPLICATION_JSON) { if(jsonObject != null && !jsonObject.isEmpty()) { httpPost.setEntity(new StringEntity(jsonObject.toString(),"UTF-8")); } } else if(contentType == ContentType.APPLICATION_FORM_URLENCODED) { // 设置参数 setHttpClientEntity(jsonObject, httpPost); } httpResponse = httpClient.execute(httpPost); } else if("2".equals(postType)) { //===== put =====// HttpPut httpPut = new HttpPut(url); // 设置请求头 setHttpClientHeaders(contentType, headers, httpPut); // 设置参数 setHttpClientEntity(jsonObject, httpPut); httpResponse = httpClient.execute(httpPut); } else if ("3".equals(postType)) { //===== delete =====// // HttpDelete httpDelete = new HttpDelete(url); HttpDeleteWithBody httpDelete = new HttpDeleteWithBody(url); // 设置请求头 setHttpClientHeaders(contentType, headers, httpDelete); // 设置参数 setHttpClientEntity(jsonObject, httpDelete); httpResponse = httpClient.execute(httpDelete); } // //返回结果 // entity = httpResponse.getEntity(); // String s = EntityUtils.toString(entity, "utf-8"); // EntityUtils.consume(entity); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (URISyntaxException e) { e.printStackTrace(); } return httpResponse; } public static String initJSessionId(URL url) { CookieStore cookieStore = new BasicCookieStore(); HttpClientContext context = HttpClientContext.create(); cookieStore = new BasicCookieStore(); // 配置超时时间(连接服务端超时1秒,请求数据返回超时2秒) RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(120000).setSocketTimeout(60000) .setConnectionRequestTimeout(60000).build(); // 设置默认跳转以及存储cookie CloseableHttpClient httpClient = HttpClientBuilder.create().setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy()) .setRedirectStrategy(new DefaultRedirectStrategy()).setDefaultRequestConfig(requestConfig) .setDefaultCookieStore(cookieStore).build(); HttpGet httpget = new HttpGet(url.toString()); CloseableHttpResponse response = null; try { response = httpClient.execute(httpget, context); cookieStore = context.getCookieStore(); List<Cookie> cookies = cookieStore.getCookies(); for (Cookie cookie : cookies) { System.out.println("name = " + cookie.getName() + ", value = " + cookie.getValue()); if("JSESSIONID".equalsIgnoreCase(cookie.getName())) { return cookie.getValue(); } } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if(response != null) { try { response.close(); } catch (IOException e) { e.printStackTrace(); } } } throw new RuntimeException("未获取到 JSESSIONID"); } /** * 根据响应获取响应实体 * * @param response * @return */ public static <T> T getContent(CloseableHttpResponse response, Class<T> clazz) { HttpEntity entity = response.getEntity();// 获取响应实体 T content = null; try { if(content instanceof String) { content = (T) EntityUtils.toString(entity, "utf-8");// 用string接收响应实体 } else if(clazz.isArray()) { content = (T) EntityUtils.toByteArray(entity); } EntityUtils.consume(entity);// 消耗响应实体,并关闭相关资源占用 } catch (ParseException e1) { e1.fillInStackTrace(); } catch (Exception e1) { e1.fillInStackTrace(); } finally { release(response); } return content; } public static String getContent(CloseableHttpResponse response) { HttpEntity entity = response.getEntity(); StringBuffer sb = new StringBuffer(); try(BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"), 8*1024);) { String line = null; while ((line=bufferedReader.readLine())!=null) { sb.append(line + "\n"); } //利用从HttpEntity中得到的String生成JsonObject System.out.println("sb = " + sb.toString()); return sb.toString(); } catch (Exception e) { e.printStackTrace(); } return null; } public static void release(CloseableHttpResponse response) { if(response != null) { try { response.close(); } catch (IOException e) { e.printStackTrace(); } } } private static void setHttpClientHeaders(ContentType contentType, Map<String, String> headers, HttpRequestBase httpClient) { httpClient.setHeader("Content-type", contentType.getMimeType()); httpClient.setHeader("DataEncoding", "UTF-8"); if(headers != null && !headers.isEmpty()) { for (Map.Entry<String, String> entry : headers.entrySet()) { httpClient.setHeader(entry.getKey(),entry.getValue()); } } } private static void setHttpClientEntity(JSONObject jsonObject, HttpEntityEnclosingRequestBase httpClient) throws UnsupportedEncodingException { if(jsonObject != null && !jsonObject.isEmpty()) { List<NameValuePair> list = new LinkedList<>(); for (Map.Entry<String,?> entry : jsonObject.entrySet()) { list.add(new BasicNameValuePair(entry.getKey(), jsonObject.getString(entry.getKey()))); } UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(list); httpClient.setEntity(formEntity); } } @NotThreadSafe static class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase { public static final String METHOD_NAME = "DELETE"; @Override public String getMethod() { return METHOD_NAME; } public HttpDeleteWithBody(final String uri) { super(); setURI(URI.create(uri)); } public HttpDeleteWithBody(final URI uri) { super(); setURI(uri); } public HttpDeleteWithBody() { super(); } } public static void main(String[] args) throws IOException { // String jsessionId = RandomStringUtils.randomAlphanumeric(32).toUpperCase(); // String path = "http://localhost:8888/crm"; // String path = "http://192.168.1.136:8037/crm"; URL url = new URL("http","192.168.1.136",8037,"/crm"); System.out.println(url.toString()); String jsessionId = initJSessionId(url); // jsessionId是服务器颁发的 这点很重要 String ocrCode = getOCRCode(url, "/res/Kaptcha.jpg", jsessionId); loginCRM(url, "/login_checkUser.json","superadmin","29AD0E3FD3DB681FB9F8091C756313F7","99999999",ocrCode,jsessionId); } public static void loginCRM(URL url, String res, String userName, String password, String usercode, String kaptchaCode, String jsessionId) { List<BasicClientCookie> clientCookies = new ArrayList<>(); BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", jsessionId); cookie.setDomain(url.getHost()); cookie.setPath(url.getFile()); cookie.setSecure(false); clientCookies.add(cookie); JSONObject jsonObject = new JSONObject(); jsonObject.put("username",userName); jsonObject.put("password",password); jsonObject.put("usercode",usercode); jsonObject.put("kaptchaCode",kaptchaCode); CloseableHttpResponse response = httpClient("1", url.toString() + res, ContentType.APPLICATION_FORM_URLENCODED, null, clientCookies, jsonObject); String content = getContent(response); System.out.println("content = " + content); } public static String getOCRCode(URL url, String res, String jsessionId) throws IOException { List<BasicClientCookie> clientCookies = new ArrayList<>(); BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", jsessionId); cookie.setDomain(url.getHost()); // 这里设置domain和path不能省去 cookie.setPath(url.getFile()); cookie.setSecure(false); clientCookies.add(cookie); CloseableHttpResponse response = httpClient("0", url.toString() + res, ContentType.APPLICATION_FORM_URLENCODED, null, clientCookies, null); byte[] bytes = getContent(response, byte[].class); String uuid = UUID.randomUUID().toString(); String tempPath = System.getProperty("java.io.tmpdir"); String path = tempPath + File.separator + uuid + ".jpg"; try(BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(bytes)); BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(path))) { int len = 0; byte[] buf = new byte[512]; while((len = bis.read(buf)) != -1) { bos.write(buf,0,len); } } catch (Exception e) { e.printStackTrace(); } File imageFile = new File(path); ITesseract instance = new Tesseract(); // JNA Interface Mapping URL tessdataUrl = HttpExecutor.class.getClassLoader().getResource("tessdata"); instance.setDatapath(tessdataUrl.getPath().substring(1)); // path to tessdata directory instance.setLanguage("eng"); try { String result = instance.doOCR(imageFile); // System.out.println(result); return ApiHandlerUtils.removeCRLF(result); } catch (TesseractException e) { System.err.println(e.getMessage()); } finally { if(imageFile != null && imageFile.exists() && imageFile.isFile()) { imageFile.delete(); } } return null; }
本文来自博客园,作者:margo,转载请注明原文链接:https://www.cnblogs.com/ZMargo/articles/12063738.html