1

i have a code to request an Database Entry over an API. But i have to send a JSON Object instead of Parameter.

Code is as bellow:

    public static void main(String[] args) throws Exception {
      URL url = new URL("https://example.com/api/user?method=GetUserData&key=1234567890");
        Map<String,Object> params = new LinkedHashMap<>();

        params.put("chash","709e8b37182e36092750bebbbf96bc3");
        StringBuilder postData = new StringBuilder();
        for (Map.Entry<String,Object> param : params.entrySet()) {
            if (postData.length() != 0) postData.append('&');
            postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
            postData.append('=');
            postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
        }
        byte[] postDataBytes = postData.toString().getBytes("UTF-8");

        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencode");
        conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
        conn.setDoOutput(true);
        conn.getOutputStream().write(postDataBytes);

        Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

        for (int c; (c = in.read()) >= 0;)
            System.out.print((char)c);
    }

But, of course it get an Error that the chash is not set.

How can i POST as RAWDATA JSONObject instead of that params.put(...)

Thank you in advice

T-Hope

T-Hope
  • 11
  • 1
  • 1
    try to use retrofit or any other library it makes your life easy https://square.github.io/retrofit/ – Tabish Hussain Feb 07 '17 at 13:41
  • Whilst possible to do it manually, you would find it much more manageable to use a library for this task such as Retrofit https://square.github.io/retrofit/ – Kuffs Feb 07 '17 at 13:42
  • Possible duplicate of [Sending a JSON HTTP POST request from Android](http://stackoverflow.com/questions/13911993/sending-a-json-http-post-request-from-android) – Murat Karagöz Feb 07 '17 at 13:43

0 Answers0