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");
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?