Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();   }   
like image 714
Libathos Avatar asked Dec 17 '12 10:12

Libathos


People also ask

Can we send JSON in post request?

To post JSON to a REST API endpoint, you must send an HTTP POST request to the REST API server and provide JSON data in the body of the POST message. You also need to specify the data type in the body of the POST message using the Content-Type: application/json request header.

How do I request post on Android?

build(); Request request = new Request. Builder() . url("https://yourdomain.org/callback.php") // The URL to send the data to .

Is it possible to send JSON request with HTTP GET method?

To answer your question, yes you may pass JSON in the URI as part of a GET request (provided you URL-encode).


2 Answers

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.

like image 200
Harish Avatar answered Sep 28 '22 13:09

Harish


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
like image 21
Amir Qayyum Khan Avatar answered Sep 28 '22 13:09

Amir Qayyum Khan