如何在Android上使用Apache HttpClient查看完整的HttpPost请求

时间:2013-10-10 15:31:08

标签: android forms post apache-httpclient-4.x

所以我有一些代码来构建一个HttpPost请求,如下所示......

public LoginForm apa;
....
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("https", 
SSLSocketFactory.getSocketFactory(), 443));
HttpParams httpparams = new BasicHttpParams();
SingleClientConnManager mgr = new SingleClientConnManager(httpparams, schemeRegistry);
HttpClient httpclient = new DefaultHttpClient(mgr, httpparams);
try {
  List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
  for(String i : apa.getParams().keySet()){
  nameValuePairs.add(new BasicNameValuePair(i, apa.getParams().get(i)));
}
List<NameValuePair> cookies = new ArrayList<NameValuePair>();
StringBuilder sb = new StringBuilder();
for(String i : apa.getCookies().keySet()){
  sb.append(i);
  sb.append("=");
  sb.append(apa.getCookies().get(i));
  sb.append(";");
}
// Trying to remove last ;
String cookie = sb.toString();
cookie = cookie.substring(0, cookie.length()-1);
HttpPost httppost = new HttpPost(URL);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httppost.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
httppost.setHeader("Cookie", cookie);
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
System.out.println(EntityUtils.toString(response.getEntity()));

它没有像我期望的那样完全登录,所以有没有办法输出整个请求(标题和所有)以与我在Chrome开发工具中看到的相匹配?我在想这个吗?是否有Android或Java的表单登录库?我是否需要添加内容长度?

1 个答案:

答案 0 :(得分:4)

打印标题很简单 - 您可以使用方法getAllHeaders列出标题。 如果您需要打印HttpEntity,可以使用方法writeTo将整个实体写入ByteArrayOutputStream并使用toString创建字符串。