林不完全反應做一個簡單的HTTP GET,安卓HTTPGET的BufferedReader
我看到我的結果不完全有效, 什麼即時做錯了什麼?
這裏的代碼:
class GetDocuments extends AsyncTask<URL, Void, Void> {
@Override
protected Void doInBackground(URL... urls) {
Log.d("mensa", "bajando");
//place proper url
connect(urls);
return null;
}
public static void connect(URL[] urls)
{
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpGet httpget = new HttpGet("http://tiks.document.dev.chocolatecoded.com.au/documents/api/get?type=tree");
// Execute the request
HttpResponse response;
try {
response = httpclient.execute(httpget);
// Examine the response status
Log.d("mensa",response.getStatusLine().toString());
// Get hold of the response entity
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
// to worry about connection release
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
String result= convertStreamToString(instream);
// now you have the string representation of the HTML request
Log.d("mensa", "estratagema :: "+result);
JSONObject jObject = new JSONObject(result);
Log.d("mensa", "resposta jObject::"+jObject);
Log.d("mensa", "alive 1");
JSONArray contacts = null;
contacts = jObject.getJSONArray("success");
Log.d("mensa", "resposta jObject::"+contacts);
Log.d("mensa", "alive");
//instream.close();
}
} catch (Exception e) {}
}
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");
Log.d("mensa", "linea ::"+line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
我把它用:
GetDocuments get = new GetDocuments();
URL url = null;
try {
url = new URL("ftp://mirror.csclub.uwaterloo.ca/index.html");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//URL url = new URL("http://www.google.es");
get.execute(url);
編輯1 我指的是不完全作爲被截斷的反應如何?
請注意以下響應的形象字符串被截斷如何,
這是因爲日誌的大小? 但另一個問題是,它不解析?
的感謝!
您可以更多地指定您的INCOMPLETE響應。我試着調試你的代碼並引發JSONException。 09-23 14:04:42.045:E/a(507):org.json.JSONException:值類型爲java.lang.Boolean的成功時爲true無法轉換爲JSONArray – edisonthk
我沒有得到異常,也請參閱編輯檢查截斷字符串的響應,tnx – MaKo
呵呵,我得到了異常,因爲我在你的代碼上做了一些編輯。在你的GetDocuments類連接方法,添加日誌到你的異常,然後你會看到它 – edisonthk