概述
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;
}
最后
以上就是怕孤独麦片为你收集整理的发送HTTP请求返回301和从HttpResponse中获取Cookie解决方案的全部内容,希望文章能够帮你解决发送HTTP请求返回301和从HttpResponse中获取Cookie解决方案所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复