2015-09-07 99 views
0

您好我使用下面的代碼,但我不能從urliStream。該url返回一個JSON數組。android inputstream不能從服務器頁面

URL url = new URL(tomato_search); 
URLConnection urlConnection = url.openConnection(); 
InputStream iStream = new BufferedInputStream(urlConnection.getInputStream()); 
readStream(iStream); 
iStream.close(); 
+0

也許你需要調用urlConnection.connect()之前的getInputStream() – BNK

+0

什麼都沒有發生我的PHP文件是:打印(json_encode($輸出)); – charilaos13

+0

嘗試檢查resp代碼,如果它是> = 400,getErrorStream而不是getInputStream – BNK

回答

0

如果您使用http進行通信,最好使用HttpURLConnection。

JsonArray jsonArray; 
HttpURLConnection httpURLConnection = (HttpURLConnection) new URL("http://www.example.com/endpoint").openConnection(); 
httpURLConnection.setRequestMethod("GET"); 
httpURLConnection.setRequestProperty("Content-Type", "application/json;charset=utf-8"); 
httpURLConnection.connect(); 
InputStream is = httpsURLConnection.getInputStream(); 
try { 
     BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8")); 
     StringBuilder sb = new StringBuilder(); 
     while (br.readLine() != null) { 
      sb.append(br.readLine()).append("\n"); 
     } 
     br.close(); 

     jsonArray = new JSONArray(sb.toString()); 
    } catch (IOException | JSONException e) { 
     jsonArray = null; 
    } 
+0

我只是想得到輸入流返回,因爲然後我使用readstream(iStream)方法獲取Json對象,如下所示:{JSONArray jarray = new JSONArray(in);對於(int i = 0; i charilaos13

+0

我使用此代碼從我的服務器獲取數據(json對象/數組)。我做了一個壞的副本,過去很抱歉。再次檢查代碼;) – xiaomi

+0

Sry的問題,但我有點混淆。爲什麼使用String和新的行char來獲取輸入流?什麼是Constants.DEBUG ... for? – charilaos13