cookie管理与Java的URLConnection [英] Cookie management with Java URLConnection
问题描述
我是相当新到Android编程和最近取得成功的HTTP POST请求,才得知我的Cookie也不会被存储随后的后/ GET请求之间。我看了看周围的interweb,并找到了Android的客户端的Apache和Java的HttpURLConnection的几个例子。我是在实施这两种方法到我目前的类不成功,所以我想知道,如果有人有更多的经验可以审查我的code和提供建议。
回顾:
- 我最初的POST请求成功和验证。
- 我的第二个POST请求不从最初的POST请求保留区。
- 有没有为什么有人会选择Apache的方法或Java实现的具体实例或原因是什么?都在他们自己的权利等于或做一件更提供的功能和灵活性比其他?
任何帮助是AP preciated,谢谢你。
webCreate.java
进口android.util.Log;进口java.io.BufferedReader中;
进口java.io.DataOutputStream中;
进口java.io.InputStreamReader中;
进口java.net.CookieHandler;
进口java.net.CookieManager;
进口java.net.HttpCookie;
进口java.net.HttpURLConnection中;
进口的java.net.URL;进口javax.net.ssl.HttpsURLConnection中;公共类webCreate { 私人最终字符串USER_AGENT =Mozilla的/ 5.0;
// HTTP GET请求
公共无效sendGet(字符串URL)抛出异常{ CookieManager cookieManager =新CookieManager();
CookieHandler.setDefault(cookieManager);
的HttpCookie饼干=新的HttpCookie(郎,恩);
URL = OBJ新的URL(网址);
HttpURLConnection的CON =(HttpURLConnection类)obj.openConnection(); //可选默认为GET
con.setRequestMethod(GET); //添加请求头
con.setRequestProperty(用户代理,USER_AGENT); INT响应code = con.getResponse code();
Log.d(sendGet,\\ nSending'GET'请求URL:+网址);
在的BufferedReader =新的BufferedReader(
新的InputStreamReader(con.getInputStream()));
串inputLine;
StringBuffer的响应=新的StringBuffer();
而((inputLine = in.readLine())!= NULL){
response.append(inputLine);
} 附寄(); //打印结果
的System.out.println(response.toString());
Log.d(响应code,response.toString());
} // HTTP POST请求
字符串sendPost(URL字符串,字符串urlParams)抛出异常{ CookieManager cookieManager =新CookieManager();
CookieHandler.setDefault(cookieManager);
的HttpCookie饼干=新的HttpCookie(郎,恩); URL = OBJ新的URL(网址);
HttpsURLConnection的CON =(HttpsURLConnection的)obj.openConnection(); //添加请求头
con.setRequestMethod(POST);
con.setRequestProperty(用户代理,USER_AGENT);
con.setRequestProperty(接受语言,EN-US,连接; Q = 0.5); //发送POST请求
con.setDoOutput(真);
DataOutputStream类WR =新的DataOutputStream类(con.getOutputStream());
wr.writeBytes(urlParams);
wr.flush();
wr.close(); INT响应code = con.getResponse code();
的System.out.println(\\ nSendingPOST请求URL:+网址);
的System.out.println(后的参数:+ urlParams);
的System.out.println(响应code:+响应code); 在的BufferedReader =新的BufferedReader(
新的InputStreamReader(con.getInputStream()));
串inputLine;
StringBuffer的响应=新的StringBuffer(); 而((inputLine = in.readLine())!= NULL){
response.append(inputLine);
}
附寄(); 的System.out.println(响应code:+响应);
返回response.toString();
}}
您需要保持你的cookie的外部环境给每个呼叫并提供相同的cookie存储它在随后的GET和POST。这是为Java实现和Apache的实现都是相同的。
在我的经验, Apache的HTTP组件是比内置在Java中更好实现。我花了大量时间试图写使用Java开发的一种工具,我的最大的问题是超时。糟糕的Web服务器将挂起从而导致连接无限期挂起。切换到Apache后,超时是可调的,我们没有任何更多的挂起线程。
我将使用Apache举一个例子。
在你的父类的方法创建的CookieStore
实例:
的CookieStore的CookieStore =新BasicCookieStore();
然后在你的GET或POST实现通过在的CookieStore
实例,当你建立HttpClient的使用它:
公共无效sendGet(字符串URL,的CookieStore的CookieStore)抛出异常{
...
HttpClient的客户端= HttpClientBuilder.create()setDefaultCookieStore(的CookieStore).build(); HTTPGET请求=新HTTPGET(URI); //或HttpPost ...
request.addHeader(用户代理,USER_AGENT);
HTT presponse响应= client.execute(请求); BR的BufferedReader =新的BufferedReader(新的InputStreamReader(response.getEntity()的getContent()));
...
}
Android已经扩展 java.net.HttpURLConnection中的
,并建议使用这一点,所以我还会为一个大纲,作为好。
HttpURLConnection类
和 HttpsURLConnection的
自动,透明地使用 CookieManager
在的CookieHandler
设置。 的CookieHandler
是VM-宽所以必须只有一次设置。如果您创建一个新的 CookieManager
为每个请求,正如你在code一样,它会消灭在previous请求设置任何cookie。
您不必创建的HttpCookie
自己的一个实例。当 HttpURLConnection类
来自服务器的 CookieManager收到一个cookie
将接收cookie,并存储。在同一台服务器未来的请求将自动发送previously集饼干。
所以,移动这个code到您的应用程序安装,因此只发生一次:
CookieManager cookieManager =新CookieManager();
CookieHandler.setDefault(cookieManager);
I'm fairly new to android programming and recently achieved a successful HTTP Post request, only to learn that my cookies are not being stored between subsequent Post/Get requests. I looked around the interweb, and found a few examples for Android's Apache client and Java's HttpURLConnection. I was unsuccessful in implementing either method into my current class, so I was wondering if someone with more experience could review my code and offer suggestions.
Recap:
- My initial POST request is successful and authenticated.
- My second POST request does not retain the cookies from the initial POST request.
- Is there any specific instance or reason why someone might opt for the Apache method or the Java implementation? Are both equals in their own right or does one offer more capabilities and flexibility than the other?
Any help is appreciated, thank you.
webCreate.java
import android.util.Log;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.CookieHandler;
import java.net.CookieManager;
import java.net.HttpCookie;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class webCreate {
private final String USER_AGENT = "Mozilla/5.0";
// HTTP GET request
public void sendGet(String url) throws Exception {
CookieManager cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);
HttpCookie cookie = new HttpCookie("lang", "en");
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode();
Log.d("sendGet", "\nSending 'GET' request to URL : " + url);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
Log.d("Response Code", response.toString());
}
// HTTP POST request
String sendPost(String url, String urlParams) throws Exception {
CookieManager cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);
HttpCookie cookie = new HttpCookie("lang", "en");
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add request header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParams);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParams);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println("Response Code : " + response);
return response.toString();
}
}
You need to maintain your cookie context external to each call and provide the same cookie store it on subsequent GETs and POSTs. This is the same for both the Java implementation and Apache's implementation.
In my experience, Apache's HTTP components is better than the built in Java implementation. I spent a large amount of time trying to write a utility using Java's implementation, my largest problem was timeouts. Bad web servers would hang causing the connection to hang indefinitely. After switching to Apache the timeouts were tuneable and we didn't have any more hung threads.
I'll give an example using Apache.
Create the CookieStore
instance in your parent method:
CookieStore cookieStore = new BasicCookieStore();
Then in your GET or POST implementations pass in the CookieStore
instance and use it when you build the HttpClient:
public void sendGet(String url, CookieStore cookieStore) throws Exception {
...
HttpClient client = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build();
HttpGet request = new HttpGet(uri); // or HttpPost...
request.addHeader("User-Agent", USER_AGENT);
HttpResponse response = client.execute(request);
BufferedReader br = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
...
}
Android has extended java.net.HttpURLConnection
and recommends using this, so I'll also give an outline for that as well.
HttpURLConnection
and HttpsURLConnection
automatically and transparently uses the CookieManager
set in CookieHandler
. CookieHandler
is VM-wide so must be setup only once. If you create a new CookieManager
for each request, as you did in your code, it will wipe out any cookies set in previous requests.
You do not need to create an instance of HttpCookie
yourself. When HttpURLConnection
receives a cookie from the server the CookieManager
will receive the cookie and store it. Future requests to the same server will automatically send the previously set cookies.
So, move this code to your application setup so it happens only once:
CookieManager cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);
这篇关于cookie管理与Java的URLConnection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!