发送HTTP请求返回301和从HttpResponse中获取Cookie解决方案

    xiaoxiao2022-07-03  173

    1、发送HTTP请求,如何从HttpResponse中获取Cookie?

    2、发送HTTP请求返回301重定向响应吗,如何发起二次post请求,获得最终的响应?

    解决方案如下:

    private static String getCookieFromResponse(@NonNull HttpResponse response) { Header[] responseHeader = response.getHeaders("Set-Cookie"); int length = responseHeader.length; StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < length; i++) { if (responseHeader[i] != null) { if ("Set-Cookie".equals(responseHeader[i].getName())) { int index = responseHeader[i].getValue().indexOf(";"); if (i == length - 1) { stringBuilder.append(responseHeader[i].getValue().substring(0, index)); } else { stringBuilder.append(responseHeader[i].getValue().substring(0, index) + "; "); } } } } return stringBuilder.toString(); } @SuppressWarnings("deprecation") private static HttpResponse doPost(String url, List<NameValuePair> list, String charset, boolean isSetCookie, String cookieValue) throws Exception { HttpClient httpClient = SSLClient.getSingletonHttpClient(); HttpPost httpPost = new HttpPost(url); if (isSetCookie) { httpPost.addHeader("Cookie", cookieValue); } httpPost.setEntity(new UrlEncodedFormEntity(list, charset)); HttpResponse response = httpClient.execute(httpPost); if (response != null) { if (response.getStatusLine().getStatusCode() == org.apache.http.HttpStatus.SC_MOVED_PERMANENTLY) { return doPost(response.getFirstHeader("location").getValue(), list, charset, true, getCookieFromResponse(response)); } else if (response.getStatusLine().getStatusCode() == org.apache.http.HttpStatus.SC_OK) { return response; } } return response; }

     

    最新回复(0)