我正在尝试在Android应用程序中发送HTTP Post请求。
这是我应该发送的内容:
这是我应该收到的:
因此,总而言之,我需要从响应中获取cookie,响应代码应为302.
我有以下Android代码:
private static String makePostRequest() {
HttpClient httpClient = new DefaultHttpClient();
// replace with your url
HttpPost httpPost = new HttpPost("http://g1.botva.ru/login.php");
boolean flag = httpClient.getParams().isParameterTrue(ClientPNames.HANDLE_REDIRECTS);
httpPost.addHeader("Accept", "*/*");
httpPost.addHeader("Accept-Encoding", "gzip, deflate");
//httpPost.addHeader("Content-Length", "83");
httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
httpPost.addHeader("User-Agent", "runscope/0.1");
Header [] arr = httpPost.getAllHeaders();
String result123 = "";
//Post Data
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(5);
nameValuePair.add(new BasicNameValuePair("do_cmd", "login"));
nameValuePair.add(new BasicNameValuePair("server", "1"));
nameValuePair.add(new BasicNameValuePair("email", "avmalyutin@mail.ru"));
nameValuePair.add(new BasicNameValuePair("password", "avmalyutin1234"));
nameValuePair.add(new BasicNameValuePair("remember", "1"));
//Encoding POST data
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
} catch (UnsupportedEncodingException e) {
// log exception
e.printStackTrace();
}
//making POST request.
try {
HttpResponse response = httpClient.execute(httpPost);
String getCookie = response.getHeaders("Pragma").length + "";
result123 = response.getStatusLine().getStatusCode()+"";
// write response to log
Log.d("Http Post Response:", response.toString());
} catch (ClientProtocolException e) {
// Log exception
e.printStackTrace();
} catch (IOException e) {
// Log exception
e.printStackTrace();
}
return result123;
}
我收到的代码为200.而Cookie中只有PHPSESSIONID,但没有其他Cookie。
答案 0 :(得分:1)
您需要检测DefaultHttpClient,以便可以看到WIRE和HEADERS。 Google为您正在使用的客户端记录WIRE HEADERS。如果您无法弄清楚日志记录调试(您可能需要考虑DIFF client)
然后,比较做帖子的2个框架(你的测试工具VS android)只是缩小了发送标题+ POST BODY之间的差异。当你让android与你的测试工具融合时,android会产生你报告从测试工具获得的相同的302结果。
答案 1 :(得分:0)
添加功能
con.setInstanceFollowRedirects(false);
解决问题并停止重定向。我还根据需要收到了代码302.
感谢大家的帮助