1

我对 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();
    }
4

1 回答 1

1

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

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

这对我很有效......

于 2013-09-05T01:13:44.670 回答