[java] Sending a JSON HTTP POST request from Android

I'm using the code below to send an http POST request which sends an object to a WCF service. This works ok, but what happens if my WCF service needs also other parameters? How can I send them from my Android client?

This is the code I've written so far:

StringBuilder sb = new StringBuilder();  

String http = "http://android.schoolportal.gr/Service.svc/SaveValues";  


HttpURLConnection urlConnection=null;  
try {  
    URL url = new URL(http);  
    urlConnection = (HttpURLConnection) url.openConnection();
    urlConnection.setDoOutput(true);   
    urlConnection.setRequestMethod("POST");  
    urlConnection.setUseCaches(false);  
    urlConnection.setConnectTimeout(10000);  
    urlConnection.setReadTimeout(10000);  
    urlConnection.setRequestProperty("Content-Type","application/json");   

    urlConnection.setRequestProperty("Host", "android.schoolportal.gr");
    urlConnection.connect();  

    //Create JSONObject here
    JSONObject jsonParam = new JSONObject();
    jsonParam.put("ID", "25");
    jsonParam.put("description", "Real");
    jsonParam.put("enable", "true");
    OutputStreamWriter out = new   OutputStreamWriter(urlConnection.getOutputStream());
    out.write(jsonParam.toString());
    out.close();  

    int HttpResult =urlConnection.getResponseCode();  
    if(HttpResult ==HttpURLConnection.HTTP_OK){  
        BufferedReader br = new BufferedReader(new InputStreamReader(  
            urlConnection.getInputStream(),"utf-8"));  
        String line = null;  
        while ((line = br.readLine()) != null) {  
            sb.append(line + "\n");  
        }  
        br.close();  

        System.out.println(""+sb.toString());  

    }else{  
            System.out.println(urlConnection.getResponseMessage());  
    }  
} catch (MalformedURLException e) {  

         e.printStackTrace();  
}  
catch (IOException e) {  

    e.printStackTrace();  
    } catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}finally{  
    if(urlConnection!=null)  
    urlConnection.disconnect();  
}  

This question is related to java android json wcf httpurlconnection

The answer is


try some thing like blow:

SString otherParametersUrServiceNeed =  "Company=acompany&Lng=test&MainPeriod=test&UserID=123&CourseDate=8:10:10";
String request = "http://android.schoolportal.gr/Service.svc/SaveValues";

URL url = new URL(request); 
HttpURLConnection connection = (HttpURLConnection) url.openConnection();   
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false); 
connection.setRequestMethod("POST"); 
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", "" + Integer.toString(otherParametersUrServiceNeed.getBytes().length));
connection.setUseCaches (false);

DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(otherParametersUrServiceNeed);

   JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");

wr.writeBytes(jsonParam.toString());

wr.flush();
wr.close();

References :

  1. http://www.xyzws.com/Javafaq/how-to-use-httpurlconnection-post-data-to-web-server/139
  2. Java - sending HTTP parameters via POST method easily

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to wcf

Create a asmx web service in C# using visual studio 2013 WCF Exception: Could not find a base address that matches scheme http for the endpoint WCF Service, the type provided as the service attribute values…could not be found WCF error - There was no endpoint listening at How can I pass a username/password in the header to a SOAP WCF Service The HTTP request is unauthorized with client authentication scheme 'Negotiate'. The authentication header received from the server was 'NTLM' Content Type application/soap+xml; charset=utf-8 was not supported by service The content type application/xml;charset=utf-8 of the response message does not match the content type of the binding (text/xml; charset=utf-8) maxReceivedMessageSize and maxBufferSize in app.config how to generate a unique token which expires after 24 hours?

Examples related to httpurlconnection

How to get response body using HttpURLConnection, when code other than 2xx is returned? android download pdf from url then open it with a pdf reader POST request send json data java HttpUrlConnection "PKIX path building failed" and "unable to find valid certification path to requested target" Java simple code: java.net.SocketException: Unexpected end of file from server Getting java.net.SocketTimeoutException: Connection timed out in android How to send Request payload to REST API in java? Sending a JSON HTTP POST request from Android Sending files using POST with HttpURLConnection Parse JSON from HttpURLConnection object