The HttpURLConnection Why JSONObject doesn't work like Params, but String as Params does

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

      

I am getting response code as 200 which means the connection is ok, but I am getting empty variables on the PHP side, what could be wrong here?

I used to send a JSON array, but just to test functionality, I commented this, now I only send one variable key as "key"

It's amazing to see this example code works - without the JSON array and key value pair:

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

      

So it boils down to replacing this:

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

      

:

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

      

and I'm still wondering.

+3


source to share


1 answer


I believe the problem is not on the Java side here. If the parameters are of a fixed type, as in json in your case, the JSON Object as a POST params method will work if it is assembled 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");
?>

      

+5


source







All Articles