Android POST到服务器始终返回错误的响应代码

时间:2015-12-26 01:55:31

标签: java android http post http-post

我在从Android应用程序向Web服务器传递POST请求时遇到问题。我创建了一个接受POST参数的页面" data"使用字符串值,我已检查它是否适用于Google Chrome Postman扩展程序。但是,当我尝试从Android应用程序发送数据时,我总是得到一个错误的HTTP响应代码,好像数据根本没有传递给服务器。

private void sendDataToServer(final String uri, final String data) {
    Log.d("Debug", "MainActivity -> sendDataToServer (start)");
    Thread t = new Thread() {
        public void run() {

            try {
                // Set up connection
                Log.d("Debug", uri);
                HttpURLConnection urlConnection = (HttpURLConnection) ((new URL(uri).openConnection()));
                urlConnection.setRequestMethod("POST");
                urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                urlConnection.setDoInput(true);
                urlConnection.setDoOutput(true);
                urlConnection.connect();

                // Write
                OutputStreamWriter writer = new OutputStreamWriter(urlConnection.getOutputStream());
                Log.d("Debug", data);
                writer.write("data=" + data);
                writer.close();

                // Read
                int responseCode = urlConnection.getResponseCode();

                Log.d("Debug", String.valueOf(responseCode));

                if (responseCode == 200) {
                    Log.d("Debug", "Message sending: Success!");
                    // TODO: Do something with the results
                } else {
                    Log.d("Debug", "Message sending: Failure...");
                }

                urlConnection.disconnect();

            } catch (UnsupportedEncodingException e) {
                Log.d("Debug", e.getMessage());
            } catch (IOException e) {
                Log.d("Debug", e.getMessage());
            }

        }
    };
    t.start();
    Log.d("Debug", "MainActivity -> sendDataToServer (end)");
}

网络服务器的代码:

$postData = $_POST['data'];//file_get_contents("php://input");

if ($postData) {

  $connection = connectToDB();

  $array = json_decode($postData);

  foreach ($array as $element) {
    addMessage($connection, $element->timestamp, $element->sender, $element->message);
  }

  disconnectFromDB($connection);

  http_response_code(200);

} else {

  http_response_code(400);

}

我该怎么做才能解决这个问题? 我正在运行Android Lollipop。

1 个答案:

答案 0 :(得分:2)

由于您使用"Content-Type", "application/x-www-form-urlencoded"所以我建议您参考我的示例代码,如下所示:

    private class POSTRequest extends AsyncTask<Void, Void, String> {

        @Override
        protected String doInBackground(Void... voids) {
            String address = "http://...";
            HttpURLConnection urlConnection;
            String requestBody;
            Uri.Builder builder = new Uri.Builder();
            Map<String, String> params = new HashMap<>();
            params.put("key1", "value1");
            params.put("key2", "value2");            

            // encode parameters
            Iterator entries = params.entrySet().iterator();
            while (entries.hasNext()) {
                Map.Entry entry = (Map.Entry) entries.next();
                builder.appendQueryParameter(entry.getKey().toString(), entry.getValue().toString());
                entries.remove();
            }
            requestBody = builder.build().getEncodedQuery();

            try {
                URL url = new URL(address);
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setDoOutput(true);
                urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                OutputStream outputStream = new BufferedOutputStream(urlConnection.getOutputStream());
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "utf-8"));
                writer.write(requestBody);
                writer.flush();
                writer.close();
                outputStream.close();

                InputStream inputStream;
                // get stream
                if (urlConnection.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST) {
                    inputStream = urlConnection.getInputStream();
                } else {
                    inputStream = urlConnection.getErrorStream();
                }
                // parse stream
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                String temp, response = "";
                while ((temp = bufferedReader.readLine()) != null) {
                    response += temp;
                }
                // do something...                

                return response;
            } catch (IOException | JSONException e) {
                return e.toString();
            }
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            Log.i(LOG_TAG, "POST\n" + result);
        }
    }

更新:

我刚刚测试并获得了200条响应代码,其中包含以下内容:

Android(我对数据进行硬编码):

...
Map<String, String> params = new HashMap<>();
params.put("data","[{\"timestamp\":\"2015-12-26 07:02:00.557\", \"sender\":\"58576402\", \"message\":\"4\"}]");
...

PHP:

<?php
$postData = file_get_contents("php://input"); // $_POST['data'];//file_get_contents("php://input");
if ($postData) { 
  //$array = json_decode($postData);
  http_response_code(200);
} else {
  http_response_code(400);
}
?>