Executing a HTTP POST JSON Request with HttpClient
This post covers the following topics
Steps:
1. Create a new HttpClient Class
2. Create JSON Request object
3. Send Http Request and Get Response
4. Parse JSON Response object
5. Populate to ListView
In MainActivity,
- Post HTTP request containing parameters to a web server
- Get HTTP post response (JSON Response)
- Parse JSON Response
- Populate Results to ListView
Steps:
- Create a new HttpClient Class
- Create JSON Request object
- Send Http Request and Get Response
- Parse JSON Response object
- Populate to ListView
1. Create a new HttpClient Class
public class HttpClient { static URL url; static HttpURLConnection conn; static OutputStream os; static String resultString=null; public static String SendHttpPost(String URL, String req, Activity act) { try{ url=new URL(URL); conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setConnectTimeout(90000); //Connection Timeout time in mSec conn.setReadTimeout(90000); //Read Timeout time in mSec conn.setRequestProperty(HTTP.CONTENT_TYPE, "application/json"); conn.setRequestProperty("Accept", "application/json"); conn.setFixedLengthStreamingMode(req.getBytes().length); conn.connect(); //open long t = System.currentTimeMillis(); os = new BufferedOutputStream(conn.getOutputStream()); //setup send os.write(req.getBytes()); os.flush(); //clean up if (conn.getResponseCode() == HttpURLConnection.HTTP_OK){ Log.i("HttpClient", "HTTPResponse received in [" + (System.currentTimeMillis()-t) + "ms]"); //do somehthing with response Scanner inStream = new Scanner(conn.getInputStream()); //process the stream and store it in StringBuilder resultString = new String(); while(inStream.hasNextLine()) resultString+=(inStream.nextLine()); return resultString; } // handle issues if (conn.getResponseCode() == HttpURLConnection.HTTP_CLIENT_TIMEOUT){ showMsgDialogToFinish("Alert", "Request Timed out..! Plsase Try again", "Go back", act); } if (conn.getResponseCode() == HttpURLConnection.HTTP_SERVER_ERROR){ showMsgDialogToGoHome("Alert", "We are sorry the service is currently unavailable..! Please try again later.", "Go back", act); } }catch (MalformedURLException e) { } catch (SocketTimeoutException e) { } catch (IOException e) { Methods.wscContext =null; e.printStackTrace(); }finally { //clean up try { os.close(); } catch (IOException e) { e.printStackTrace(); } conn.disconnect(); } return null; } }
2. Create JSON Request object
Sample JSON request: {"username":"user","password":"smething"}
JSONObject jsonReq = new JSONObject(); try { jsonReq.put("username", username); jsonReq.put("password", pwd); } catch (JSONException e) { Log.e(TAG, "JSONException: " + e); }
3. Send Http Request and Get Response
public class GetResponse { static String jsonResponse = null; public static String getResponse(String url, Activity act){ try { String username = "user"; String pwd = "something"; String contentType = "application/json"; JSONObject jsonReq = new JSONObject(); try { jsonReq.put("username", username); jsonReq.put("password", pwd); } catch (JSONException e) { Log.e(TAG, "JSONException: " + e); } Log.i("GetResponse",">>\n"+jsonReq+"\n "); // Send the HttpPostRequest and receive a JSONObject in return jsonResponse = new String(); jsonResponse = HttpClient.SendHttpPost( url, jsonReq, act); } catch (JSONException e) { e.printStackTrace(); } return jsonResponse; } }
4. Parse JSON Response object
Sample JSON Request which is return from getResponseObj method { "MovieList": [{ "Movie": "Wreck it ralph", }, { "Movie": "Tangled", }] }
JSONObject jsonResponse; ArrayListmyMovieList = new ArrayList (); try { /* Creates a new JSONObject from the JSON string*/ jsonResponse = new JSONObject(strJson); /* Returns the value mapped by name */ JSONArray jsonMainNode = jsonResponse.getJSONArray("MovieList"); int lengthJsonArr = jsonMainNode.length(); for(int i=0; i < lengthJsonArr; i++) { /****** Get Object for each JSON node.***********/ JSONObject jsonChildNode = jsonMainNode.getJSONObject(i); /******* Fetch node values **********/ String movie_name = jsonChildNode.optString("Movie").toString(); myMovieList.add(movie_name); }
5. Populate to ListView
In MainActivity,
public class MainActivity extends Activity{ ListView listView; @Override protected void onCreate(BundlesavedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.myLayout); //GetListView object from xml listView=(ListView)findViewById(R.id.list); //use our myMovieList data ArrayAdapterSample Output:adapter=new ArrayAdapter (this,android.R.layout.simple_list_item_1,android.R.id.text1,myMovieList); //Assign adapter to ListView listView.setAdapter(adapter); //ListViewItemClickListener listView.setOnItemClickListener(newOnItemClickListener(){ @Override public void onItemClick(AdapterViewparent,Viewview,intposition,longid){ //ListView Clicked item index int itemPosition=position; //ListView Clicked itemvalue StringitemValue=(String)listView.getItemAtPosition(position); //ShowAlert Toast.makeText(getApplicationContext(),"Position :"+itemPosition+" ListItem : "+itemValue,Toast.LENGTH_LONG).show(); } }); } }