Tuesday 9 October 2012

Get json array by using get or post Request


 


 


public static void CopyStream(InputStream is, OutputStream os)



throws Exception {



final int buffer_size = 1024;



byte[] bytes = new byte[buffer_size];



for (;;) {



int count = is.read(bytes, 0, buffer_size);



if (count == -1)



break;


os.write(bytes, 0, count);

}

}



 


public static String makePostRequest(String url,


List<NameValuePair> nvp) {

Log.e(url,

"");


String result =

"";



try {


HttpClient client =

new DefaultHttpClient();


HttpPost post =

new HttpPost(url);


post.setEntity(

new UrlEncodedFormEntity(nvp));


HttpResponse httpResponse = client.execute(post);

HttpEntity httpEntity = httpResponse.getEntity();




if (httpEntity != null) {


InputStream inputStream = httpEntity.getContent();

result = convertStreamToString(inputStream);

inputStream.close();

client =

null;


post.abort();

}

}

catch (Exception e) {


Log.e(

"ee", ""+e.getMessage());


e.printStackTrace();

}


return result;


}



 


public static String makePostRequest1(String url,


List<NameValuePair> nameValuePair) {

String result =

null;



try {


HttpClient httpclient =

new DefaultHttpClient();


HttpPost httppost =

new HttpPost(url);


httppost.setEntity(

new UrlEncodedFormEntity(nameValuePair));



//Log.e("httppost", ""+httppost);



if (httppost != null) {


HttpResponse response = httpclient.execute(httppost);

Log.e(

"response", ""+response);



if (response != null) {


InputStream is = response.getEntity().getContent();

result = convertStreamToString(is);

is.close();

}

httpclient =

null;


httppost.abort();

}


}

catch (SocketException e) {


}

catch (UnknownHostException e) {


}

catch (Exception e) {



//Log.e("ee111", ""+e.getMessage());


}

catch (Error e) {



//Log.e("ee", ""+e.getMessage());



// TODO: handle exception


}


return result;


}




public static String getJSONData(String url) throws Exception {


Log.d(

"url ", ""+url);


String result =

"";


{

HttpClient httpClient =

new DefaultHttpClient();


HttpGet httpGet =

new HttpGet(url);


HttpResponse httpResponse = httpClient.execute(httpGet);

HttpEntity httpEntity = httpResponse.getEntity();


if (httpEntity != null) {


InputStream inputStream = httpEntity.getContent();

result = convertStreamToString(inputStream);

inputStream.close();

httpClient =

null;


httpGet.abort();

}


return result;


}

}




private static String convertStreamToString(InputStream is)



throws Exception {


BufferedReader reader =

new BufferedReader(new InputStreamReader(is));


StringBuilder sb =

new StringBuilder();


String line =

null;



while ((line = reader.readLine()) != null) {


sb.append(line +

"\n");


}

is.close();

reader.close();


//Log.e("sb",""+sb.toString());



return sb.toString();

}

No comments:

Post a Comment