经过三天的搜索和阅读关于HttpUrlConnection和CookieManager的资料,我发现有很多关于它的问题,还有更多关于如何发送Cookies的问题。
因此,我为此提供了一个完整的解决方案:
处理Cookies的方法如下:
static CookieManager myCookies = new CookieManager(null, CookiePolicy.ACCEPT_ALL);
final public static void saveCookies(HttpURLConnection connection , Context context) {
Map<String, List<String>> headerFields = connection.getHeaderFields();
List<String> cookiesHeader = null;
try {
cookiesHeader = headerFields.get("Set-Cookie");
} catch (Exception e) {
e.printStackTrace();
}
if (cookiesHeader != null && myCookies != null) {
for (String cookie : cookiesHeader) {
try {
cookie = cookie.replace("\"", "");
myCookies.getCookieStore().add(connection.getURL().toURI(), HttpCookie.parse(cookie).get(0));
String new_cookie = TextUtils.join(";", myCookies.getCookieStore().getCookies());
PreferenceManager.getDefaultSharedPreferences(context).edit().putString("cookie", new_cookie).commit();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
final public static void loadCookies(HttpURLConnection connection , Context context) {
if (myCookies != null && myCookies.getCookieStore().getCookies().size() > 0) {
connection.setRequestProperty("Cookie", TextUtils.join(";", myCookies.getCookieStore().getCookies()));
}
else {
String new_cookie = PreferenceManager.getDefaultSharedPreferences(context).getString("cookie" , "");
connection.setRequestProperty("Cookie", new_cookie );
}
}
使用 Json 数据进行 Post 请求
public String URL_Connectin_Post ( String endPoint , JSONObject data , Context context )
{
URL url;
try {
url = new URL(baseUrl + endPoint);
urlConnection = (HttpURLConnection) url.openConnection();
loadCookies(urlConnection , context);
urlConnection.setReadTimeout(15000);
urlConnection.setConnectTimeout(15000);
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("charset", "UTF-8");
urlConnection.addRequestProperty("Accept-Encoding", "UTF-8");
urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
urlConnection.setFixedLengthStreamingMode(data.toString().getBytes("UTF-8").length);
urlConnection.setUseCaches(true);
urlConnection.setRequestMethod("POST");
urlConnection.connect();
OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(os, "UTF-8"));
writer.write(data.toString());
writer.flush();
writer.close();
os.close();
int responseCode=urlConnection.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK)
{
InputStream in = urlConnection.getInputStream();
saveCookies(urlConnection , context);
Result = convertStreamToString(in);
}
} catch (Exception e) {
e.printStackTrace();
}
return Result;
}
获取请求
public String URL_Connectin_Get(String endPoint , Context context)
{
URL url;
try {
url = new URL(baseUrl + endPoint);
urlConnection = (HttpURLConnection) url.openConnection();
loadCookies(urlConnection , context);
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("charset", "UTF-8");
urlConnection.addRequestProperty("Accept-Encoding", "UTF-8");
urlConnection.setDoInput(true);
urlConnection.setRequestMethod("GET");
urlConnection.connect();
int responseCode=urlConnection.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
InputStream in = urlConnection.getInputStream();
if (urlConnection.getContentEncoding() != null && urlConnection.getContentEncoding().contains("gzip")) {
GZIPInputStream inn = new GZIPInputStream(in);
saveCookies(urlConnection , context);
} else {
saveCookies(urlConnection , context);
}
Result = convertStreamToString(in);
}
} catch (IOException e) {
e.printStackTrace();
}
return Result ;
}
HttpURLConnection
是 SDK 的一部分。如果您不想使用第三方 HTTP 客户端,它是自然的替代品。 - Blackbelt