Java tutorial
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package net.GoTicketing; import java.io.BufferedInputStream; import java.io.IOException; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import static net.NET_INFO.DEFAULT_PARAMS; import org.apache.http.Header; import org.apache.http.HttpStatus; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; /** * ???? cookie * @author Jasper */ public class GetNecessaryCookie { private static final Logger logger = Logger.getLogger(GetNecessaryCookie.class.getName()); public static void getCookie(String host, String referer, String target, Map<String, String> cookieMap) { try (CloseableHttpClient httpClient = HttpClients.createDefault()) { HttpGet httpGet = new HttpGet(host + target); httpGet.setConfig(DEFAULT_PARAMS); String cookies = CookieMapToString(cookieMap); if (!cookies.equals("")) httpGet.setHeader("Cookie", cookies); httpGet.setHeader("Referer", host + referer); try (CloseableHttpResponse httpResponse = httpClient.execute(httpGet)) { // HttpStatusCode != 200 && != 404 if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK && httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_NOT_FOUND) { String ErrorCode = "Response Status : " + httpResponse.getStatusLine().getStatusCode(); throw new IOException(ErrorCode); } try (BufferedInputStream buff = new BufferedInputStream(httpResponse.getEntity().getContent())) { String hstr; for (Header header : httpResponse.getHeaders("Set-Cookie")) { hstr = header.getValue().split(";")[0]; cookieMap.put(hstr.split("=", 2)[0], hstr.split("=", 2)[1]); } } } } catch (IOException ex) { logger.log(Level.WARNING, "Get cookie from {0} failed in exception : {1}", new Object[] { target, ex }); } } /** * CookieMap ? http request * @param CookieMap Map ? cookie * @return http request */ public static String CookieMapToString(Map<String, String> CookieMap) { StringBuilder CookieBuilder = new StringBuilder(); CookieMap.forEach((key, value) -> { CookieBuilder.append("; ").append(key).append("=").append(value); }); if (CookieBuilder.length() > 2) return CookieBuilder.substring(2); else return CookieBuilder.toString(); } }