我使用以下类连接到我的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; }}
最佳答案除了Ladlestein评论中的所有可能的解决方案之外,还有一个简单的答案就是将所有这些解压缩到AsyncTask中. 总结 以上是内存溢出为你收集整理的java – 如何在Android上建立异步URL连接?全部内容,希望文章能够帮你解决java – 如何在Android上建立异步URL连接?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)