在HttpURLConnection中为什么不将JSONObject作为Params工作但String as Params正在工作

时间:2015-05-19 10:57:03

标签: java php android httpurlconnection jsonobject

我正在使用HttpUrlConnection将一些数据发布到我的服务器这里是函数:

private String register(String myurl) throws IOException {

        String resp = null;
        try {
            JSONObject parameters = new JSONObject();
           // parameters.put("jsonArray", ((makeJSON())));
            parameters.put("key", "key");//getencryptkey());
            URL url = new URL(myurl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //  conn.setReadTimeout(10000 /* milliseconds *///);
            //  conn.setConnectTimeout(15000 /* milliseconds */);
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");
            OutputStream out = new BufferedOutputStream(conn.getOutputStream());
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
            writer.write(parameters.toString());
            writer.close();
            out.close();

            int responseCode = conn.getResponseCode();
            System.out.println("\nSending 'POST' request to URL : " + url);
            System.out.println("Response Code : " + responseCode);

            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();


            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            System.out.println("strngbuffr" + response.toString());
            resp = response.toString();

        } catch (Exception exception) {
            System.out.println("Exception: " + exception);
        }

        System.out.println("rsp"+ resp.toString());
        return resp.toString();
    }

我得到的响应代码为200,这意味着连接没问题但是我在PHP端获得了空变量,这里有什么不对吗?

早些时候我也发送了一个JSON数组,但只是为了测试功能性我评论说现在我只发送一个变量key as "key"

令人惊讶的是,这个示例代码可以工作 - 没有JSON数组和键值对:

private String sendPost(String url) throws Exception {

        String USER_AGENT = "Mozilla/5.0";
        URL obj = new URL(url);

        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        //add reuqest header
        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", USER_AGENT);
        con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        String urlParameters ="sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";
        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + urlParameters);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();

        //print result
        System.out.println("rvsp"+response.toString());

        return response.toString();
    }

所以归结为替换它:

 JSONObject parameters = new JSONObject();
            parameters.put("jsonArray", new JSONArray(Arrays.asList(makeJSON())));
            parameters.put("key", getencryptkey()); 

由此:

String urlParameters ="jArr="+makeJSON()+"Key="+getencryptkey();

我仍然很好奇。

1 个答案:

答案 0 :(得分:5)

我认为这里的问题不在Java方面,如果参数是固定类型的,就像在你的情况下在json中一样,如果在php端以这种方式收集,则JSON对象作为POST params方法将起作用:

<?php
    $json = file_get_contents('php://input');
    $obj = json_decode($json);
    print_r($obj);
    print_r("this is a test response");
?>