How To Fetch Jsondata In Server Through Android?
I am developing a new android application.I have all the data in server.. How I can fetch the JSONData through android?? I am confused there are HttpGet,HttpClient,HttpUrlConnecti
Solution 1:
I suggest you to use "Volley" library for android .It is for faster and better networking library by Google . Many examples of using volley :
http://arnab.ch/blog/2013/08/asynchronous-http-requests-in-android-using-volley/
Solution 2:
Try this code, Its working fine in my project:-
public String connect(){
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicypolicy=newStrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
InputStreamis=null;
//the year data to send/*nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("year","1980"));*///http post
System.out.println("url----------"+url);
System.out.println("url----------"+get_nameValuePairs);
try{
HttpClienthttpclient=newDefaultHttpClient();
HttpPosthttppost=newHttpPost(url);
httppost.setEntity(newUrlEncodedFormEntity(get_nameValuePairs));
HttpResponseresponse= httpclient.execute(httppost);
HttpEntityentity= response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to stringtry{
BufferedReaderreader=newBufferedReader(newInputStreamReader(is,"iso-8859-1"),8);
StringBuildersb=newStringBuilder();
Stringline=null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
//System.out.println("query Result:----------"+result);
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
// parse json datatry{
JSONArrayjArray=newJSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObjectjson_data= jArray.getJSONObject(i);
//val.add(json_data.getString("password"));//data.append(json_data.getString("first_name")+"\n");//System.out.println(i+"Data found---"+json_data.getString("first_name"));
}
//System.out.println(val);
}catch(JSONException e){
Log.e("log_tag inside database", "Error parsing data "+e.toString());
}
/*Log.d("Inside dataBase", result);*/return result;
}
Solution 3:
private String sendRequestInternal(String url, String body) throws MalformedURLException, IOException {
Log.i(TAG, "request:\nURL:"+url);
HttpURLConnection connection=null;
try{
connection = (HttpURLConnection)new URL(url).openConnection();
connection.setConnectTimeout(30000);
connection.setReadTimeout(30000);
connection.setRequestMethod("GET");// "POST","PUT" etc.if (body != null) {
connection.setDoOutput(true);
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(body);
writer.flush();
writer.close();
}
InputStream is = null;
int code = connection.getResponseCode();
Log.i(TAG, "code=" + code);
if ((code / 100) < 4) {
is = new BufferedInputStream(connection.getInputStream()); // OK
} else {
is = new BufferedInputStream(connection.getErrorStream()); // Exception while executing request
}
String response = convertStreamToString(is);
return response;
} finally {
if (connection != null)
connection.disconnect();
}
}
private String convertStreamToString(InputStream is) throws IOException {
InputStreamReader r = new InputStreamReader(is);
StringWriter sw = new StringWriter();
char[] buffer = newchar[1024];
try {
for (int n; (n = r.read(buffer)) != -1;)
sw.write(buffer, 0, n);
}
finally{
try {
is.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
return sw.toString();
}
With the help of the method sendRequestInternal
you can get a String from the server.
Next you should parse depends on JSON that the server returns to you. For example server returns next JSON data:
{"data":"OK","reason":"user","status":200}
You can parse this next:
publicvoidparseJSON(String json) {
JSONObject realJson = newJSONObject(json);
String dataValue = realJson.getString("data");
int status = realJson.getInt("status");
Log.d(TAG, dataValue + " " status);
}
Post a Comment for "How To Fetch Jsondata In Server Through Android?"