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
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!!
3 Comments
Goran
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 :)
Anand Sainath
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!
Anand Sainath
Or if that's too big, even this post might help ya!