【问题标题】:Sending Json POST Android - Data not added发送 Json POST Android - 未添加数据
【发布时间】:2013-09-05 00:50:44
【问题描述】:

我在使用 post 方法时遇到了一些问题:似乎数据没有被添加到请求中。我的 json 对象(下面的 jObject)是 {"FirstName":"John"},但响应是 {"FirstName":"Peter"}。为什么 POST 不能处理这个请求?

   @Override
    protected Void doInBackground(Void... arg) {
          DefaultHttpClient httpClient = new DefaultHttpClient();
          HttpPost request = new HttpPost(someUrl);

          ResponseHandler <String> responseHandler = new BasicResponseHandler();
          request.setHeader("Content-type", "application/json");
          StringEntity se = new StringEntity(jObject.toString());
          se.setContentEncoding("UTF-8");
          se.setContentType("application/json");
          request.setEntity(se);

          String authorizationString = "Basic " + Base64.encodeToString(("username" + ":" + "password").getBytes(), Base64.NO_WRAP);
          request.addHeader("Authorization", authorizationString);

          String response = httpClient.execute(request, responseHandler);

编辑:我最初检索数据的方式

   // Initialize url and create connection
    URL url = new URL(urlSpec);
    HttpURLConnection connection = (HttpURLConnection)url.openConnection();
    byte[] auth = (email_login + ":" + password_login).getBytes();
        String basic = Base64.encodeToString(auth, Base64.NO_WRAP);
        httpConn.setRequestProperty("Authorization", "Basic " + basic);
    // Retrieve data
    try{
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        InputStream in = connection.getInputStream();

        if(connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            return null;
        }

        int bytesRead = 0;
        byte[] buffer = new byte[1024];
        while ((bytesRead = in.read(buffer)) > 0) {
            out.write(buffer, 0, bytesRead);
        }
        out.close();
        return out.toByteArray();
    } finally {
        connection.disconnect();
    }

【问题讨论】:

  • 您确定您发送的请求实际上是发送“彼得”吗?您发布的代码看起来正确,这可能是服务器端问题吗?
  • 是的。还有其他字段,但这是我正在编辑的唯一字段。
  • 示例。 jObject:{"FirstName":"John", "LastName":"Doe",...}。回复是{"FirstName":"Peter", "LastName":"Doe",...}
  • 您是说服务器的响应显示“Peter”,您确定服务器代码是正确的并且由于某种原因并不总是返回“Peter”吗?我还会查看 Charles Proxy 以确认发送到服务器的数据是错误的。没有意义的是,如果您的 json 对象有 John,就像您说的那样,请求将如何与 Peter 进行切换?我认为 http post 问题不可能以某种方式仅更改您请求中的某些文本,并且不仅保持 json 结构完整,而且还插入了另一个随机人名。
  • 查看我的编辑,它可能会有所帮助。这就是我检索包含“Peter”的原始 Json 的方式。 (这样我就可以获取数据并对其进行处理)。这个想法是让某人登录并能够更改他们的信息,例如名字。一旦他们这样做了,我就会尝试将其重新捕获到 Json 对象中并将数据作为请求发送,这是我最初的问题。

标签: android json http-post


【解决方案1】:

尝试设置以UTF8字节数组编码的json数据,如下:

request.setEntity(new ByteArrayEntity(
postMessage.toString().getBytes("UTF8")));

这对我很有效...

【讨论】:

  • 所以摆脱所有StringEntity se
  • 你能在服务器端检查一下那里有什么吗?
  • 回应?这是一个 Json 字符串,但它不会更新数据字段。它仍然是“彼得”而不是“约翰”。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-25
  • 1970-01-01
相关资源
最近更新 更多