It is a very common task that android applications have to request and recieve from web service where data are in JSON format. Here the task is implemented using a very simple method that takes the web service url and request parameters as JSON object and it returns what it obtains from the server as a JSON object. The main component of this method is the HttpURLConnection class.
The line con.setDoOutput(true); enables to send request body and the line con.setRequestMethod(“POST”); setting the request method as POST. The line con.setRequestProperty(“Content-Type”, “application/json”); designates the content to be in JSON format and the line con.setRequestProperty(“Accept”, “application/json”); setting json is acceptable for response. The line con.setReadTimeout(10000); sets the time 10 seconds for receiving data after establishing connection and the line con.setConnectTimeout(15000); sets the time out for 15 seconds for establishing connection.
public static JSONObject doPostRequest(String url, JSONObject jsonReq){ JSONObject jsonRes = null; try { URL urlObj = new URL(url); HttpURLConnection con; con = (HttpURLConnection) urlObj.openConnection(); con.setDoOutput(true); con.setRequestProperty("Content-Type", "application/json"); con.setRequestProperty("Accept", "application/json"); con.setRequestMethod("POST"); con.setReadTimeout(10000); con.setConnectTimeout(15000); byte[] outputBytes = jsonReq.toString().getBytes("UTF-8"); OutputStream os = con.getOutputStream(); os.write(outputBytes); os.flush(); os.close(); //Receive the response from the server InputStream in = new BufferedInputStream(con.getInputStream()); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder result = new StringBuilder(); String strLine; while ((strLine = reader.readLine()) != null) { result.append(strLine); } con.disconnect(); jsonRes = new JSONObject(result.toString()); }catch (Exception e){ Log.e("Exception", e.toString()); } // return JSON Object return jsonRes; }