我正在将 Web 应用程序移植到 Android,但我有一个问题。我正在从 PHP 脚本下载验证码图像,并且想要检索 cookie:
Bitmap mIcon11 = null;
try {
java.net.URL url = new java.net.URL(urldisplay);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setUseCaches(true);
connection.connect();
InputStream in = connection.getInputStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.d("Error", "NEINA SIUSTI IMAGO");
e.printStackTrace();
}
并在此处使用相同的 cookie 进行验证:
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://somesite.lt/index.php");
try {
// Add your data
List < NameValuePair > nameValuePairs = new ArrayList < NameValuePair > (2);
nameValuePairs.add(new BasicNameValuePair("phoneno", ((EditText) findViewById(R.id.number)).getText().toString()));
nameValuePairs.add(new BasicNameValuePair("phbody", ((EditText) findViewById(R.id.sms)).getText().toString()));
nameValuePairs.add(new BasicNameValuePair("captcha_code", ((EditText) findViewById(R.id.code)).getText().toString()));
nameValuePairs.add(new BasicNameValuePair("agree", "on"));
nameValuePairs.add(new BasicNameValuePair("submit", ""));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Log.d("ers", "ENtit " + nameValuePairs.toString());
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost, mHttpContext);
我该怎么做?从 URLConnection 检索 cookie 并在 HTTPPost 请求中使用它们。
谢谢!
最佳答案
耶!找到了解决方案。我在验证码中确实得到了:
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
java.net.URL url = new java.net.URL(urldisplay);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setUseCaches(true);
connection.connect();
String cookie = connection.getHeaderField("Set-Cookie");
cookie = cookie.substring(0, cookie.indexOf(';'));
mSes = cookie;
InputStream in = connection.getInputStream();
mIcon11 = BitmapFactory.decodeStream(in);
在页面验证上:
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://somesite.lt/index.php");
httppost.addHeader("Cookie", mSes);
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("phoneno", ((EditText)findViewById(R.id.number)).getText().toString()));
nameValuePairs.add(new BasicNameValuePair("phbody", ((EditText)findViewById(R.id.sms)).getText().toString()));
nameValuePairs.add(new BasicNameValuePair("captcha_code", ((EditText)findViewById(R.id.code)).getText().toString()));
nameValuePairs.add(new BasicNameValuePair("agree", "on"));
nameValuePairs.add(new BasicNameValuePair("submit", ""));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Log.d("ers","ENtit "+nameValuePairs.toString());
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost, mHttpContext);
关于java - Android 通过 HttpPost 和 URLconnection 使用 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13422164/