GorkemSahin GorkemSahin - 1 year ago 45
Java Question

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:

Web Service code by server's side:

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.

Answer Source

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();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download