Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8101685
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 5, 20262026-06-05T23:02:33+00:00 2026-06-05T23:02:33+00:00

I have used httpclient to call a restapi written in django. It returned the

  • 0

I have used httpclient to call a restapi written in django. It returned the json output. My httpresponse variable stored it and later convert the reponse to string and then to json object, i think its lengthy though it is working . I am really new to java , can anybody advise me , what is the best alternative logic to 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();
    }   
}
});

the json is as follows

{"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"}]}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-05T23:02:35+00:00Added an answer on June 5, 2026 at 11:02 pm

    Use Gson library from google, it is perfect for these kind of tasks.

    All you need to do is define a new class that contains fields with the names of the keys in the json object and then use Gson to parse the Json string directly into the object or vice versa.

    So for example:

    Json looks like this: "limit": 20, "next": null, "offset": 0, "previous": null, "total_count": 1.

    Java Class will be:

    public class MyClass {
        private int limit;
        private int next;
        private int offset;
        private int previous;
        private int total_count;
    
    public int getLimit() {
        return limit;
    }
    public void setLimit(int limit) {
        this.limit = limit;
    }
    public int getNext() {
        return next;
    }
    public void setNext(int next) {
        this.next = next;
    }
    public int getOffset() {
        return offset;
    }
    public void setOffset(int offset) {
        this.offset = offset;
    }
    public int getPrevious() {
        return previous;
    }
    public void setPrevious(int previous) {
        this.previous = previous;
    }
    public int getTotal_count() {
        return total_count;
    }
    public void setTotal_count(int total_count) {
        this.total_count = total_count;
    }
    }
    

    And use Gson code like that:

     Gson gson = new Gson(); // Or use new GsonBuilder().create();
     MyClass myClass = gson.fromJson(json, MyClass.class); // deserializes json into MyClass 
    

    Please note that the name of the class fields have to match exactly the name of the keys in the json string.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

i am try to call webservice using Android.I have used httpclient as well as
Any examples, tips, guidance for the following scenario? I have used Apache HttpClient to
I have used the following code on my client side (Android emulator). HttpClient client=new
I have a class for Httpclient. The same instance is used throughout the application.
I have to call SharePoint 2010 Lists service from a Java client. I used
I'm have a java program that uses Apache httpclient api. This is used to
I have only one httpclient in my 1st activity which is used in all
I have used the following as comments in my .emacs // {{{ // }}}
I have used the following article as a guide to creating a custom EditorPart
I have used JQuery for a small animation work: a table #photos contains 9

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.