使用HttpUrlConnection发送JSON数据时获取空$ _POST

时间:2017-10-25 12:50:26

标签: java php android json httpurlconnection

我正在尝试使用HttpUrlConnection从Android应用程序发送POST请求,但是我的php脚本中的空$ _POST或奇怪格式的JSON数据。

我认为问题在于我设置RequestProperty Content类型的方式,因为当我将它设置为" application / json;字符集= UTF-8" $ _POST为空,当我将其设置为" application / x-www-form-urlencoded;字符集= UTF-8" $ _POST是{" {\" forename \":\" Joe \",\"姓氏":\"史密斯\"}":""}

理想情况下,我希望采用格式{" forename":" Joe","姓氏":" Smith&# 34;},因为我的php脚本将数据处理为$ _POST [" forename"},$ _POST [" surname"}等等。

编辑: 玩了一遍,发现如果我做了

$raw_post = file_get_contents('php://input');

在我的PHP代码中,然后$ raw_post将是{" forename":" Joe"," surname":" Smith"} ,这是理想的效果。 但是,$ _POST仍为空。虽然$ raw_post工作,但感觉就像一个hacky解决方法。 使用$ _POST不是正确的方法吗?

编辑#2:编辑#2: 我最终实现了最终解决方案/解决方法:

$raw_post = json_decode(file_get_contents('php://input'), true);

" true"参数将输入解码为PHP数组,因此我能够以$ raw_post [" forename"]的形式访问键值。这仍然无法解决通过$ _POST访问的问题,因此我会将此问题保持打开状态,但这是一个充分的解决方法。

我的Java代码如下......

class postToServer extends AsyncTask<String, String, String>
{
    @Override
    protected String doInBackground(String... args) {
        StringBuilder sb = new StringBuilder();
        try {
            URL url = new URL(url_create_customer);
            con = (HttpURLConnection) url.openConnection();
            con.setDoOutput(true);
            con.setDoInput(true);
            //con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
            con.setRequestProperty("Accept", "application/json");
            con.setRequestMethod("POST");

            JSONObject custy = new JSONObject();
            custy.put("forename", args[0]);
            custy.put("surname", args[1]);

            OutputStream os = con.getOutputStream();
            os.write(custy.toString().getBytes("UTF-8"));  
            os.close();

            //display what returns the POST request
            int HttpResult = con.getResponseCode();
            System.out.println(HttpResult);
            if (HttpResult == HttpURLConnection.HTTP_OK) {
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(con.getInputStream(), "utf-8"));
                String line = null;
                while ((line = br.readLine()) != null) {
                    sb.append(line + "\n");
                }
                br.close();
                System.out.println("" + sb.toString());
            } else {
                System.out.println(con.getResponseMessage());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            con.disconnect();
        }
        return sb.toString();
    }
}

0 个答案:

没有答案