GorkemSahin
GorkemSahin

Reputation: 69

How to post a JSON object as body?

I created the JSON object using this code:

json = new JSONObject();
    try {
        json.put("success", true);
        JSONObject jCustomer = new JSONObject();
        jCustomer.put("LOGICALREF", 0);
        jCustomer.put("CODE", "");
        EditText definitionText = (EditText) findViewById(R.id.definitionText);
        jCustomer.put("DEFINITION_", definitionText.getText().toString());
        jCustomer.put("ISPERSCOMP", isPersComp);
        EditText taxOrIdNoText = (EditText) findViewById(R.id.taxOrIdNoText);
        if (isPersComp == 1){
            jCustomer.put("TAXNR", "");
            jCustomer.put("TCKNO", taxOrIdNoText.getText().toString());
        } else {
            jCustomer.put("TAXNR", taxOrIdNoText.getText().toString());
            jCustomer.put("TCKNO", "");
        }
        EditText taxOfficeText = (EditText) findViewById(R.id.taxOfficeText);
        String taxOfficeString = taxOfficeText.getText().toString();
        if (taxOfficeString.isEmpty() || taxOfficeString == null){
            jCustomer.put("TAXOFFICE", "TCKIMLIK");
        } else {
            jCustomer.put("TAXOFFICE", taxOfficeString);
        }
        EditText emailText = (EditText) findViewById(R.id.emailText);
        jCustomer.put("EMAILADDR", emailText.getText().toString());
        EditText address1Text = (EditText) findViewById(R.id.address1Text);
        jCustomer.put("ADDR1", address1Text.getText().toString());
        EditText address2Text = (EditText) findViewById(R.id.address2Text);
        jCustomer.put("ADDR2", address2Text.getText().toString());
        jCustomer.put("CITY", cityString);
        jCustomer.put("CITYCODE", cityNo);
        jCustomer.put("TOWN", townString);
        jCustomer.put("TOWNCODE", townNo);
        EditText inChargeText = (EditText) findViewById(R.id.inChargeText);
        jCustomer.put("INCHARGE", inChargeText.getText().toString());
        EditText nameText = (EditText) findViewById(R.id.nameText);
        jCustomer.put("NAME", nameText.getText().toString());
        EditText surnameText = (EditText) findViewById(R.id.surnameText);
        jCustomer.put("SURNAME", surnameText.getText().toString());
        EditText phoneNo1Text = (EditText) findViewById(R.id.phoneNo1Text);
        jCustomer.put("TELNRS1", phoneNo1Text.getText().toString());
        EditText phoneNo2Text = (EditText) findViewById(R.id.phoneNo2Text);
        jCustomer.put("TELNRS2", phoneNo2Text.getText().toString());
        json.put("data", jCustomer);
        new postJSON().execute();
    } catch (Exception e){
        e.printStackTrace();
    }

postJSON is a private class that extends AsyncTask. Here is its code:

private class postJSON extends AsyncTask<Void, Void, Void>{
    ProgressDialog progressDialog;

    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog = new ProgressDialog(NewCustomerInfoActivity.this);
        progressDialog.setMessage("Yeni müşteri kaydediliyor. Lütfen bekleyiniz.");
        progressDialog.setCancelable(false);
        progressDialog.show();
    }

    @Override
    protected Void doInBackground(Void... arg0) {
        // Don't know what to do here...
        return null;
    }

    protected void onPostExecute(Void requestResult) {
        super.onPostExecute(requestResult);
        if (progressDialog.isShowing()) {
            progressDialog.dismiss();
        }

    }
}

Now I have to post this to the server as body, and I don't know where to begin. Most tutorials on the internet use libraries that I can't add or find, or are too complicated for me to understand. I already created a webRequest function but I use it to get the JSON objects from the server and it works:

public String getJson (String urlAdress, Boolean postRequest){
    URL url;
    String jString = "";
    try {
        url = new URL(urlAdress);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setReadTimeout(15001);
        connection.setReadTimeout(15001);
        connection.setDoInput(true);
        if (postRequest){
            connection.setRequestMethod("POST");
        } else {
            connection.setRequestMethod("GET");
        }
        int requestResponse = connection.getResponseCode();
        if (requestResponse == HttpsURLConnection.HTTP_OK){
            String line;
            BufferedReader buffer = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            while ((line = buffer.readLine()) != null){
                jString += line;
            }
        } else {
            jString = "";
        }
    } catch (Exception e){
        e.printStackTrace();
        return null;
    }
    return jString;
}

How do I add the JSON object to the url as body and post it? Will the function above suffice when it comes to posting it?

Edit after adding the recommended codes (outputstream etc.):

Web Service code by server's side:

@RequestMapping(value = "/newCustomer", method = RequestMethod.POST, headers = "Accept=application/json; charset=utf-8", produces = "application/json")
private ResponseEntity<String> newCustomer (@RequestParam(value = "deviceId") String _deviceId,
              @RequestParam(value = "ssid") String _ssid,
              @RequestBody String _incomingData, //(value = "incomingData")
              HttpServletRequest _request,HttpServletResponse _response){
        Object responseMap = null;

        boolean response = false;
        System.out.println(_incomingData);

Incoming data to the server:

deviceId=ec5f501b01c54038&ssid=QUCGFHA7ILIT3E9O8BHTD5NE4H&%7B%22success%22%3Atrue%2C%22data%22%3A%7B%22LOGICALREF%22%3A0%2C%22CODE%22%3A%22%22%2C%22DEFINITION_%22%3A%22asdasd%22%2C%22ISPERSCOMP%22%3A0%2C%22TAXNR%22%3A%22564564%22%2C%22TCKNO%22%3A%22%22%2C%22TAXOFFICE%22%3A%22ghfgh%22%2C%22EMAILADDR%22%3A%22asdasd%22%2C%22ADDR1%22%3A%22asdas%22%2C%22ADDR2%22%3A%22asdasd%22%2C%22CITY%22%3A%22Amasya%22%2C%22CITYCODE%22%3A5%2C%22TOWN%22%3A%22Hamam%C3%83%C2%B6z%C3%83%C2%BC%22%2C%22TOWNCODE%22%3A3%2C%22INCHARGE%22%3A%22xcvxcb%22%2C%22NAME%22%3A%22xcbxcb%22%2C%22SURNAME%22%3A%22gxcb%22%2C%22TELNRS1%22%3A%22456456%22%2C%22TELNRS2%22%3A%225456456%22%7D%7D=

ssId and deviceId were NOT supposed to be sent as a part of the body. Yet here it is.

The function I use at the moment:

public String postJson (String urlAdress, Boolean postRequest, JSONObject json){
    URL url;
    String jString = "";
    try {
        url = new URL(urlAdress);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setReadTimeout(15001);
        connection.setReadTimeout(15001);
        connection.setDoInput(true);
        if (postRequest){
            connection.setRequestMethod("POST");
        } else {
            connection.setRequestMethod("GET");
        }
        connection.connect();
        OutputStreamWriter request = new OutputStreamWriter(connection.getOutputStream());
        request.write(json.toString());
        request.flush();
        int requestResponse = connection.getResponseCode();
        if (requestResponse == HttpsURLConnection.HTTP_OK){

        } else {
            jString = "";
        }
    } catch (Exception e){
        e.printStackTrace();
        return null;
    }
    return jString;
}

Upvotes: 1

Views: 1940

Answers (2)

Santhosh
Santhosh

Reputation: 170

Use Retrofit,

blog - https://futurestud.io/tutorials/retrofit-getting-started-and-android-client

library - http://square.github.io/retrofit

Its easy to implement just using POJO class with GSON.

Without external library,

Try this,

public static String POST(Activity context, String connectionURL,
                          YOURBODYOBJECT mparms) throws Exception {

    try {
        url = new URL(connectionURL);
        connection = (HttpURLConnection) url.openConnection();
        connection.setReadTimeout(30000);
        connection.setConnectTimeout(30000);
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded"); // Change header for your convience.
        connection.setChunkedStreamingMode(0);
        connection.setRequestMethod("POST");
        connection.connect();
        request = new OutputStreamWriter(connection.getOutputStream());
        request.write(mparms);// pass your body content
        request.flush();
        HTTP_RESPONSE_CODE = connection.getResponseCode();
        switch (HTTP_RESPONSE_CODE) {
            case HttpURLConnection.HTTP_OK:
                isr = new InputStreamReader(connection.getInputStream());
                reader = new BufferedReader(isr);
                sb = new StringBuilder();
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                // response variable.
                response = sb.toString();
                isr.close();
                reader.close();
                return response.trim();

            case HttpURLConnection.HTTP_UNAUTHORIZED:
                return String.valueOf(HTTP_RESPONSE_CODE).trim();

            case HttpURLConnection.HTTP_BAD_REQUEST:
                isr = new InputStreamReader(connection.getErrorStream());
                reader = new BufferedReader(isr);
                sb = new StringBuilder();
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }

                response = sb.toString();
                isr.close();
                reader.close();
                return response.trim();

            case HttpURLConnection.HTTP_INTERNAL_ERROR:
                isr = new InputStreamReader(connection.getErrorStream());
                reader = new BufferedReader(isr);
                sb = new StringBuilder();
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }

                response = sb.toString();
                isr.close();
                reader.close();
                return response.trim();

            default:
                return response.trim();
        }

    } catch (Exception e) {
        // Error
        return e.getMessage();

    } finally {
        connection.disconnect();
    }
}

Upvotes: -2

Krzysztof Cichocki
Krzysztof Cichocki

Reputation: 6414

Add line connection.setDoOutput(true); below the connection.setDoInput(true);.

Then get the outputStream from your HttpURLConnection and write the json there, something like this:

   OutputStream os = connection.getOutputStream();
   os.write(json.toString().getBytes("UTF-8"));
   os.close();

Upvotes: 3

Related Questions