44

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();  
}  
marcospereira
  • 12,045
  • 3
  • 46
  • 52
Libathos
  • 3,340
  • 5
  • 36
  • 61
  • follow this link. You are trying to send other params, the link blow will give you demonstration how you you can send them after encoding http://www.xyzws.com/Javafaq/how-to-use-httpurlconnection-post-data-to-web-server/139 – Amir Qayyum Khan Dec 17 '12 at 10:14

2 Answers2

58

Posting parameters Using POST:-

URL url;
URLConnection urlConn;
DataOutputStream printout;
DataInputStream  input;
url = new URL (getCodeBase().toString() + "env.tcgi");
urlConn = url.openConnection();
urlConn.setDoInput (true);
urlConn.setDoOutput (true);
urlConn.setUseCaches (false);
urlConn.setRequestProperty("Content-Type","application/json");   
urlConn.setRequestProperty("Host", "android.schoolportal.gr");
urlConn.connect();  
//Create JSONObject here
JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");

The part which you missed is in the the following... i.e., as follows..

// Send POST output.
printout = new DataOutputStream(urlConn.getOutputStream ());
printout.writeBytes(URLEncoder.encode(jsonParam.toString(),"UTF-8"));
printout.flush ();
printout.close ();

The rest of the thing you can do it.

vidstige
  • 12,492
  • 9
  • 66
  • 110
Harish
  • 3,122
  • 2
  • 31
  • 46
  • sorry i accepted your answer but now that i'm trying to implement it,i have encountered problems.Where do you pass your parameters? – Libathos Jan 08 '13 at 09:51
  • jsonParam Object is to send parameters. – Harish Jan 08 '13 at 10:00
  • ok but i also want to send an object..how can i achieve this? meaning i have to send now 2 json objects – Libathos Jan 08 '13 at 10:04
  • In the same way you can add another object also. – Harish Jan 08 '13 at 10:43
  • 20
    The method write(int) in the type DataOutputStream is not applicable for the arguments (String) – user1940676 Mar 05 '14 at 09:20
  • 12
    Instead of write(int); I used String str = jsonString.toString(); byte[] data=str.getBytes("UTF-8"); printout.write(data); printout.flush (); printout.close (); It is working. – Thirumalvalavan Jun 01 '15 at 11:50
  • 1
    It's an old answer, but it worked great for me to move away from the deprecated DefaultHttpClient. I also moved from the deprecated NameValuePair to a JSON Object. BTW,I had to change the "write" to "writeBytes". – G O'Rilla Jul 22 '15 at 15:11
  • printout.write(URLEncoder.encode(jsonParam.toString(),"UTF-8")); we are directly pass jsonObject to server. – Harish Aug 13 '15 at 11:12
  • 1
    I was getting the error explained above, wrong parameter types for printout.write(), so I used printout.writeUTF(URLEncoder.encode(params.toString(), "UTF-8")); – jperl Mar 16 '16 at 18:40
  • If you used the above is it working fine or Are you facing any problem..? – Harish Mar 17 '16 at 07:13
  • Which are the libraries? pls – diego matos - keke Apr 28 '16 at 15:10
14

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
Community
  • 1
  • 1
Amir Qayyum Khan
  • 473
  • 2
  • 15
  • well i did that but i still get a bad request as a server response.Now let me ask if i did everything corect :When i set the otherparameter should i put param1 or the name of my parameters?also,my json object is the first parameter so first i write this one and after that i write the otherparameters is that right? – Libathos Dec 17 '12 at 10:59
  • On server side the param sequence does not matter.It seems you are puting json in payload ... in this `otherParametersUrServiceNeed = "param1=a&param2=b&param3=c";` put the name of parameters that you server need this is just example ..You should first identify the parameters that you server need in request the add these params and there values in `String otherParametersUrService` as my example demonstrates. – Amir Qayyum Khan Dec 17 '12 at 11:09
  • If it is not confidential you can tell me what addition params your server need ..so that i can put them in above example . – Amir Qayyum Khan Dec 17 '12 at 11:10
  • Well it's not,it is okay if i give you the method signature??:long InsertStudentAbsences(SRV_Students_Absence objStudentAbsences, string Company, string Lng, string MainPeriod, string UserID, string CourseDate); – Libathos Dec 17 '12 at 11:16
  • do you need something else?? – Libathos Dec 17 '12 at 11:43
  • assuming params exactlty maps on function params.These are params u need ` String otherParametersUrServiceNeed = Company=acompany&Lng=test&MainPeriod=test&UserID=123&CourseDate=xyz` – Amir Qayyum Khan Dec 17 '12 at 12:43
  • I dont know what is this object `SRV_Students_Absence objStudentAbsences` – Amir Qayyum Khan Dec 17 '12 at 12:43
  • this is just a custom object and i used a JsonObject to create one and pass it so how do i pass this object with the other parameters? – Libathos Dec 17 '12 at 12:46
  • are u sure ..your web service is serializing and deserializing the json object..i mean it can is converting json from payload to object – Amir Qayyum Khan Dec 17 '12 at 13:04
  • if you are sure there try out ` String otherParametersUrServiceNeed = Company=acompany&Lng=test&MainPeriod=test&UserID=123&CourseDate=xyz` your other params – Amir Qayyum Khan Dec 17 '12 at 13:05
  • still i don't get how i can pass as a parameter both my custom object and the other parameters – Libathos Dec 17 '12 at 13:40
  • you will pass other params same as json object...just like http request arrange parameter and values in String `String otherParametersUrServiceNeed = "Company=acompany&Lng=test&MainPeriod=test&UserID=123&CourseDate=8:10:10";` and write that string on request.just like example shows..Server should able to map these parameter name Company on String Company ....s on.You have to define mapping on server side – Amir Qayyum Khan Dec 17 '12 at 13:46
  • what is you web service interface and mapping approach...look into them and identify the parameter services want ..because parameter name are case sensitive.You have to find exact name..see request to java variable mapping approch – Amir Qayyum Khan Dec 17 '12 at 13:49
  • @AmirQayyumKhan, what is **urlParameters** in your answer – Pankaj Nimgade Nov 27 '15 at 10:46
  • where do you get Integer.toString(urlParameters.getBytes().length)) ???. – Han Whiteking Apr 17 '17 at 05:39
  • @PankajNimgade urlparams=> otherParametersUrServiceNeed – Amir Qayyum Khan Apr 17 '17 at 05:53