I used httpclient to call restapi written in django. He returned json output. My httpresponse variable saved it, and later converts the response to a string and then to a json object, I think it is lengthy, although it works. I'm really new to java, can someone advise me what is the best alternative logic for the code below
public void onClick(View v) { // TODO Auto-generated method stub HttpClient httpclient = new DefaultHttpClient(); HttpGet httppost = new HttpGet("http://10.0.2.2:8000/api/ca/entry/? format=json&username=pragya"); try { // Add your data //List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); //nameValuePairs.add(new BasicNameValuePair("username", un.getText().toString())); //nameValuePairs.add(new BasicNameValuePair("username", pw.getText().toString())); //httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = httpclient.execute(httppost); HttpEntity entity = response.getEntity(); InputStream is = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = null; try { while ((line = reader.readLine()) != null) { sb.append((line + "\n")); } } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } try { JSONObject jsonObject = new JSONObject(sb.toString()); JSONObject meta = jsonObject.getJSONObject("meta"); String limit = meta.getString("limit"); Toast.makeText(HelloWorldActivity.this, limit, Toast.LENGTH_SHORT).show(); JSONArray array = jsonObject.getJSONArray("objects"); String key = array.getJSONObject(0).getString("api_key"); String uname = array.getJSONObject(0).getString("username"); Toast.makeText(HelloWorldActivity.this, uname + " " + key, Toast.LENGTH_SHORT).show(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } //Toast.makeText(HelloWorldActivity.this, sb.toString(), Toast.LENGTH_SHORT).show(); } catch (ClientProtocolException e) { Toast.makeText(HelloWorldActivity.this, e.toString(), Toast.LENGTH_SHORT).show(); // TODO Auto-generated catch block } catch (IOException e) { // TODO Auto-generated catch block Toast.makeText(HelloWorldActivity.this, e.toString(), Toast.LENGTH_SHORT).show(); } } });
json looks like this
{"meta": {"limit": 20, "next": null, "offset": 0, "previous": null, "total_count": 1}, "objects": [{"api_key": "c87391754b522d0c83b2c8b5e4c8cfd614559632deee70fdf1b48d470307e40e", "homeAddress": "kathmandu", "resource_uri": "/api/ca/entry/1/", "username": "sumit"}]}
java json android
hangman Jun 18 2018-12-18T00: 00Z
source share