Reputation: 1235
I'm new to the android side of development, and one thing that I know that I wanted to try out was how to use HTTP Get. I've got the whole method setup so that the text is sent and my results come back in a string, but what I wanted to know was how to I take that string and extract just the parts I really need. for example the string comes back with
{"id":"124343","name":"somename" }
and if I just wanted to get the id part of that start how would I do that in android. I'm searching through the docs, but so far I haven't really found anything and then most of what I do find revolves around using JSON as well.
Below is the code I'm currently using (which I've compiled together from several different posts) but maybe I need to switch to using JSON for parsing purposes and I'm just not sure where to make that change
//This class is called after a button is pressed and the HTTPGet string is compiled from text within a textview and a static string (this already works)
private class LongRunningGetIO extends AsyncTask<Void, Void, String> {
protected String getASCIIContentFromEntity(HttpEntity entity)
throws IllegalStateException, IOException {
InputStream in = entity.getContent();
StringBuffer out = new StringBuffer();
int n = 1;
while (n > 0) {
byte[] b = new byte[4096];
n = in.read(b);
if (n > 0)
out.append(new String(b, 0, n));
}
return out.toString();
}
@Override
protected String doInBackground(Void... params) {
HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
String question = questionText.getText().toString();
String newString = httpPath + "?userText=" + question;
Log.i("Message", newString);
HttpGet httpGet = new HttpGet(newString);
String text = null;
try {
HttpResponse response = httpClient.execute(httpGet,
localContext);
HttpEntity entity = response.getEntity();
text = getASCIIContentFromEntity(entity);
} catch (Exception e) {
return e.getLocalizedMessage();
}
return text;
}
protected void onPostExecute(String results) {
if (results != null) {
Log.i("String", results);
}
}
}
Upvotes: 0
Views: 2905
Reputation: 2783
Is this what you want::
HttpGet httpGet = new HttpGet(newString);
String text = null;
try {
HttpResponse response = httpClient.execute(httpGet, localContext);
InputStream content = response.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
while ((text = buffer.readLine()) != null) {
//Work with "text" here...
//Split the string as you wish with "text.split();" function..
}
} catch (Exception e) {
return e.getLocalizedMessage();
}
Upvotes: 1
Reputation: 874
This is how to extract data from JSON string
JSONObject obj = new JSONObject(YourJSONString);
String id = obj.getString("id");
String name = obj.getString("name");
Upvotes: 2