【问题标题】:android use HttpPost and StringEntityandroid 使用 HttpPost 和 StringEntity
【发布时间】:2016-11-07 09:33:08
【问题描述】:

这是我的第一个项目。当我使用 Post 时,我无法将数据发送到服务器。

这是我的代码:

JSONObject json = new JSONObject();
        try
        {          json.put("_username", mUsername);
                   json.put("_password", mPassword);
                   String s=json.toString();
                   System.out.println("string: " + s);
                   StringEntity se = new StringEntity( s,HTTP.UTF_8);
                   System.out.println("0.string: " + se);
                   se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded"));
                   System.out.println("1.string: " + se);
                   httpRequest.setEntity(se);

还有catch (Exception e) 这是logcat

07-05 13:09:57.731 16809-16809/com.ad_imagine.jsonconnection I/System.out: string: {"_username":"lorem@ipsum.fr","_password":"aze"}
07-05 13:09:57.733 16809-16809/com.ad_imagine.jsonconnection I/System.out: 0.string: org.apache.http.entity.StringEntity@3117948
07-05 13:09:57.733 16809-16809/com.ad_imagine.jsonconnection I/System.out: 1.string: org.apache.http.entity.StringEntity@3117948
07-05 13:09:57.768 16809-16809/com.ad_imagine.jsonconnection I/System.out: 6.Exception: null

org.apache.http.entity.StringEntity@3117948 是什么?为什么 0.string 不正确?

【问题讨论】:

  • 为什么你发送 JSON 数据却告诉服务器它的表单数据?
  • 你能说明你希望你的 POST 请求是什么样子吗?

标签: android android-json androidhttpclient


【解决方案1】:

org.apache.http.entity.StringEntity@3117948 是什么?

org.apache.http.entity.StringEntity@3117948se.toString() 的结果。 StringEntity 似乎没有覆盖toString(),因此使用了Object.toString() 的实现,它只返回<FullyQualifiedClassName>@<hashCode>

为什么 0.string 不正确?

你不能说它不正确。你必须阅读se.getContent()

【讨论】:

  • 您不必添加se.toString(),编译器会为您添加。 System.out.println("0.string: " + se);System.out.println("0.string: " + se.toString()); 完全一样。您必须调用 se.getContent() 并从中读取。
  • 但是如何更改代码?我希望se 成为_username=lorem@ipsum.fr&_password=aze,然后我可以将其发送到服务器
  • se的内容是{"_username":"lorem@ipsum.fr","_password":"aze"}
  • 我添加了getContent(),它变成了` 0.string: java.io.ByteArrayInputStream@714c3e1`
  • StringEntity 类在InputStreamse.getContent() 返回的对象)中包装了一个字符串(在您的情况下,s 中的一些 JSON 数据)。如果你不想从InputStream 取回字符串,请看这里:stackoverflow.com/questions/309424/…
猜你喜欢
  • 2012-11-05
  • 1970-01-01
  • 1970-01-01
  • 2012-08-30
  • 2013-01-11
  • 2015-04-03
  • 2016-02-29
  • 2014-04-04
  • 1970-01-01
相关资源
最近更新 更多