我对android编程非常陌生,最近成功实现了成功的HTTP Post请求,只是得知在后续的Post / Get请求之间没有存储我的cookie.我环顾了互联网,发现了一些Android的Apache客户端和Java的HttpURLConnection的示例.我无法在当前类中实现这两种方法,因此我想知道是否有更多经验的人可以查看我的代码并提出建议.
概括:
>我的初始POST请求成功并通过了身份验证.
>我的第二个POST请求没有保留初始POST请求中的cookie.
>是否存在任何特定的实例或原因,为什么有人会选择Apache方法或Java实现?两者都是平等的,还是一个比另一个提供更多的功能和灵活性?
任何帮助表示赞赏,谢谢.
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();
}
}
解决方法:
您需要在每个调用外部维护cookie上下文,并提供相同的cookie存储在后续的GET和POST中. Java实现和Apache实现都是相同的.
以我的经验,Apache’s HTTP components优于内置的Java实现.我花了大量时间尝试使用Java的实现编写实用程序,我最大的问题是超时.错误的Web服务器将挂起,导致连接无限期挂起.切换到Apache之后,超时是可调整的,并且我们没有更多的挂起线程.
我将举一个使用Apache的例子.
在您的父方法中创建CookieStore实例:
CookieStore cookieStore = new BasicCookieStore();
然后在您的GET或POST实现中传递CookieStore实例,并在构建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扩展了java.net.HttpURLConnection并建议使用它,因此我还将对此进行概述.
HttpURLConnection和HttpsURLConnection自动透明地使用CookieHandler中设置的CookieManager. CookieHandler在VM范围内,因此只能设置一次.如果像在代码中那样为每个请求创建一个新的CookieManager,它将清除先前请求中设置的所有cookie.
您不需要自己创建HttpCookie的实例.当HttpURLConnection从服务器接收cookie时,CookieManager将接收cookie并将其存储.将来对同一服务器的请求将自动发送先前设置的cookie.
因此,请将此代码移至您的应用程序设置,使其仅发生一次:
CookieManager cookieManager = new CookieManager();
CookieHandler.setDefault(cookieManager);