0

Ok, i am new to all this android developement. I am trying to make an app that can log in to a webpage, and i was being told that i need to use JSON. I tried to read about this, and tried to find some examples. But everything is so little cleared. Can someone provide me with step by step explanation, what do i need to do. Thank you very much in advance.

1 Answer 1

1

Ok here goes,

First because you said you need to login to a website, you will definitely have to send the website some login credentials. Ideally you will want that also to be a JSON object.

private static String SendAndReceive(final JsonObject Json) {
    HttpClient HClient = new DefaultHttpClient();
    HttpPost HPost = new HttpPost(Constants.POST_URL);
    HttpResponse HResponse = null;
    String SResponse = null;

    try {
        List<NameValuePair> NVP = new ArrayList<NameValuePair>();
        NVP.add(new BasicNameValuePair("jsondata", Json.toString()));
        HPost.setEntity(new UrlEncodedFormEntity(NVP));
        HResponse = HClient.execute(HPost);
        if (HResponse != null) {
            InputStream in = HResponse.getEntity().getContent();
            SResponse = convertStreamToString(in);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return SResponse;
}

private static String convertStreamToString(InputStream InStream) {
    BufferedReader BReader = new BufferedReader(new InputStreamReader(
            InStream));
    StringBuilder SBuilder = new StringBuilder();
    String TmpLine = null;

    try {
        while ((TmpLine = BReader.readLine()) != null) {
            SBuilder.append(TmpLine + "\n");
        }
    } catch (Exception E) {
        E.printStackTrace();
    } finally {
        try {
            InStream.close();
        } catch (Exception E) {
            E.printStackTrace();
        }
    }
    return SBuilder.toString();
}

So now that you know how to post data to a URL and retrieve its contents, you will just have to parse your resulting JSON data. I recommend using GSON API. Hope this helps you!!

Sign up to request clarification or add additional context in comments.

3 Comments

Where do I need to put this part you wrote. in my Main Activity java file. Or i must create something new ?? I what i must do with this GSON. sorry but i am noob, i hope you can help :)
You can put these functions up in the same activity class. If you are going to build up a proper app, I suggest you keep such utility functions in a separate class. As far as GSON goes, here is a tutorial for it!
Or if that's too big, even this post might help ya!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.