2014-01-16 41 views
0

我想使用此代碼HttpURLConnection的切割的InputStream返回

private InputStream downloadUrl(String urlString) throws IOException { 
URL url = new URL(urlString); 
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
conn.setReadTimeout(10000 /* milliseconds */); 
conn.setConnectTimeout(15000 /* milliseconds */); 
conn.setRequestMethod("GET"); 
conn.setDoInput(true); 
InputStream stream = conn.getInputStream(); 
return stream; 
} 

當我嘗試使用此輸入流得到一個字符串我缺少的beggining並最終獲得從Web服務器的inputStrem,所以它似乎正在削減一些東西。 但是使用DefaultHttpClient,HttpGet和HttpResponse的結果是好的。

private String downloadPHP(String urlString){ 


      String st = null;// aqui el XML descargado 

      DefaultHttpClient client = new DefaultHttpClient(); 
      HttpGet httpGet = new HttpGet(URL);   

      try { 
       HttpResponse execute = client.execute(httpGet); 
       InputStream content = execute.getEntity().getContent(); 
       st = StringUtils.inputStreamToString(content); 


      } 
      catch (Exception e) { 
       //Log.i(Constants.DEBUG_TAG, e.getMessage()); 

      } 

      return st; 
    } 

由於谷歌正在推薦使用HttpUrlConnection,有什麼想法來解決這個問題嗎?

這是從inoutstream

public static String inputStreamToString(final InputStream stream) throws IOException { 
BufferedReader br = new BufferedReader(new InputStreamReader(stream)); 
    StringBuilder sb = new StringBuilder(); 
    String line = null; 
    while ((line = br.readLine()) != null) { 
     sb.append(line + "\n"); 
    } 
    br.close(); 
    return sb.toString(); 
} 
+0

解決了它我很快測試了你的代碼,它似乎工作正常。不過,我把它全部放在同一個功能中。 「錯過開始和結束」是什麼意思? – MoRe

+1

嗨,我正在向Web服務器發出請求以從數據庫獲取一些信息。它應該返回一個xml格式的字符串,如 – Javier

+1

嗨,我正在向Web服務器發出請求以從數據庫獲取一些信息。它應該返回一個字符串在xml fomrat包括所有的標籤等。使用DefaultHttpClient一切都很好,但使用HttpUrlConnection返回的信息是worng,我缺少第一個標籤的一部分(文檔中的第一個),信息被切入 – Javier

回答

2

我們再次檢查了代碼,也檢查了服務器端,最後發現服務器發送的數據有問題。服務器沒有以適當的格式發送數據。我們已經改變了PHP代碼,現在使用HttpUrlCOnnection,因爲它在原始問題中描述了一切正在工作。 在服務器端信息沒有得到XML格式,我們已經使用PHP DOM

0

獲取字符串試試下面的代碼從輸入流中讀取的方法。

byte[] buf;  
ByteArrayOutputStream baos = new ByteArrayOutputStream(8192); 
int read = inputStream.read(); 

while (read != -1) { 
    baos.write((byte) read); 
    read = inputStream.read(); 
} 

baos.flush(); 
buf = baos.toByteArray(); 
相關問題