duanmibei1929 2015-05-19 10:57
浏览 127
已采纳

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

I am using HttpUrlConnection to post some data to my server here is the function:

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("
Sending '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();
    }

I get the response code as 200, which means connection is okay however I get empty variables on PHP side, what can be wrong here?

Earlier I was sending a JSON array too but just to test functonality I commented that out now I am only sending one variable key as "key"

Its amazing to see, this sample code works - sans the JSON array and the key value pairs:

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("
Sending '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();
    }

So it boils down to replacing this:

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

by this:

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

and I am still curious.

  • 写回答

1条回答 默认 最新

  • drtppp75155 2015-06-25 06:37
    关注

    I reckon the problem here is not at the Java side, If the parameters is of fixed type like in json in your case, the JSON Object as POST params method will work if collected this way on the php side:

    <?php
        $json = file_get_contents('php://input');
        $obj = json_decode($json);
        print_r($obj);
        print_r("this is a test response");
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 5037端口被adb自己占了
  • ¥15 Error in check.length("fill") : 'gpar'成分'fill'的长度不能为零
  • ¥15 python:excel数据写入多个对应word文档
  • ¥60 全一数分解素因子和素数循环节位数
  • ¥15 ffmpeg如何安装到虚拟环境
  • ¥188 寻找能做王者评分提取的
  • ¥15 matlab用simulink求解一个二阶微分方程,要求截图
  • ¥30 乘子法解约束最优化问题的matlab代码文件,最好有matlab代码文件
  • ¥15 写论文,需要数据支撑
  • ¥15 identifier of an instance of 类 was altered from xx to xx错误