java - 在 HttpURLConnection 中,为什么 JSONObject 作为 Params 不起作用,但 String 作为 Params 起作用

标签 java php android httpurlconnection json

我正在使用 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();

我还是很好奇。

最佳答案

我认为这里的问题不在 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");
?>

关于java - 在 HttpURLConnection 中,为什么 JSONObject 作为 Params 不起作用,但 String 作为 Params 起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30323687/

相关文章:

java - 为什么以编程方式创建的 bean 在应用程序上下文中不可用

java - 使用 Jsoup 将链接中的表解析为字符串

java - Hibernate 连接数据库中的每个表

javascript - for循环内的jquery.load()不起作用

android - 如何从 Android 手机获得对 google.com/contacts 的读取权限?

android - getIntent.getExtras() 不返回 null,但没有值。

Java Cplex 降低最优性和第一个可行的解决方案

php - 自动维护/"We will be back"页

PHP:在界面中设置私有(private), protected ,公共(public)?

android - 这种从sqlite获取数据的方式正确吗?