大佬教程收集整理的这篇文章主要介绍了java – 如何在Android上建立异步URL连接?,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我使用以下类连接到我的Web服务.我想让这个异步.我怎样才能做到这一点?
package org.stocktwits.Helper;
import java.io.bufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.httpentity;
import org.apache.http.httpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.httpClient;
import org.apache.http.client.methods.httpGet;
import org.apache.http.impl.client.DefaulthttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class RestClient{
private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException E) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException E) {
e.printStackTrace();
}
}
return sb.toString();
}
/* This is a test function which will connects to a given
* rest service and prints it's response to Android Log with
* labels "Praeda".
*/
public static JSONObject connect(String url)
{
httpClient httpclient = new DefaulthttpClient();
// Prepare a request object
httpGet httpget = new httpGet(url);
// Execute the request
httpResponse response;
try {
response = httpclient.execute(httpget);
// Examine the response status
Log.i("Praeda",response.getStatusLine().toString());
// Get hold of the response entity
httpentity entity = response.getEntity();
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
String result= convertStreamToString(instream);
// A Simple JSONObject Creation
JSONObject json=new JSONObject(result);
// Closing the input stream will trigger connection release
instream.close();
return json;
}
} catch (ClientProtocolException E) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException E) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException E) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
以上是大佬教程为你收集整理的java – 如何在Android上建立异步URL连接?全部内容,希望文章能够帮你解决java – 如何在Android上建立异步URL连接?所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。