oldwu's Blog - 工具类
type: channel
link: https://blog.oldwu.top/index.php/tag/%E5%B7%A5%E5%85%B7%E7%B1%BB/
items: 一个好用的HttpUtils工具类

一个好用的HttpUtils工具类
type: item
date: 2021-08-21T22:29:00+08:00
description: 依赖版本号看着更新 org.apache.httpcomponents httpclient 4.5.13 org.apache.commons commons-lang3 3.12.0 实用类21.8.17 补充两个从httpResponse获取cookie的方法/** * 返回cookie * @param response * @return */ public static String getCookieString(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(); } /** * 返回Cookie * * @param httpResponse */ public static Map<String,String> getCookies(HttpResponse httpResponse) { Map<String,String> cookieContiner = new HashMap<>(); Header[] headers = httpResponse.getHeaders("Set-Cookie"); for (int i = 0; i < headers.length; i++) { String cookie = headers[i].getValue(); String[] cookievalues = cookie.split(";"); for (int j = 0; j < cookievalues.length; j++) { String[] keyPair = cookievalues[j].split("="); String key = keyPair[0].trim(); String value = keyPair.length > 1 ? keyPair[1].trim() : ""; cookieContiner.put(key, value); } } return cookieContiner; }package com.oldwu.util; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import org.apache.commons.lang3.StringUtils; import org.apache.http.HeaderElement; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.config.AuthSchemes; import org.apache.http.client.config.CookieSpecs; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpDelete; import org.apa…