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();  
}  
1
  • 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 xyzws.com/Javafaq/… Dec 17, 2012 at 10:14

2 Answers 2

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.

11
  • 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 8, 2013 at 9:51
  • 20
    The method write(int) in the type DataOutputStream is not applicable for the arguments (String) Mar 5, 2014 at 9: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. Jun 1, 2015 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, 2015 at 15:11
  • 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, 2016 at 18:40
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
16
  • 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, 2012 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. Dec 17, 2012 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 . Dec 17, 2012 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, 2012 at 11:16
  • do you need something else??
    – Libathos
    Dec 17, 2012 at 11:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.