0

OK guys, I have tried TONS of code examples the past 24 about how to do this but I couldn't get any thing to work.

I simply want to pass a JSON body to an URL. Every thing is working right using cURL in BASH, I even tried to us

Runtime.getRuntime().exec("curl.....");

but even that doesn't pass the JSON body, in fact I have succeeded in sending the http request with Runtime.getRuntime().exec(str) and couple of other ways, but NONE of them passed the JSON body.

I will appreciate any help.

Omar Elrefaei
  • 379
  • 2
  • 9

2 Answers2

0

You should use Retrofit. There are lot of samples here and here's the same question

Community
  • 1
  • 1
Anton Kazakov
  • 2,740
  • 3
  • 23
  • 34
0

If you want to write your own method: Here is a one.

private JsonObject postJsonObject(JsonObject jsonObject) {
        JsonObject nullresult = new JsonObject();
        nullresult.addProperty("success",-1);
        try {
            String data = jsonObject.toString();
            URL object = new URL(url); \\MENTION YOUR URL HERE

            HttpURLConnection httpURLConnection = (HttpURLConnection) object.openConnection();
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setRequestProperty("Content-Type", "application/json");
            httpURLConnection.setRequestProperty("Accept", "application/json");
            httpURLConnection.setRequestMethod("POST");

            httpURLConnection.setConnectTimeout(8000);
            httpURLConnection.setReadTimeout(8000);

            OutputStreamWriter wr = new OutputStreamWriter(httpURLConnection.getOutputStream());
            wr.write(data);
            wr.flush();

            StringBuilder sb = new StringBuilder();
            int HttpResult = httpURLConnection.getResponseCode();
            if (HttpResult == HttpURLConnection.HTTP_OK) {
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(httpURLConnection.getInputStream(), "utf-8"));
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line).append("\n");
                }
                br.close();
            }
            JsonObject result = new JsonParser().parse(sb.toString()).getAsJsonObject();

            if(result !=null)
                return result;
            else
                return nullresult;
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (MalformedJsonException e){
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return nullresult;
    }

You can also use a library like Ion. link: https://github.com/koush/ion

It is easy to understand networking library for android. They have examples which will help you.

Mihir Mistry
  • 86
  • 1
  • 5