2011-02-15 86 views
1

我使用此代碼對我的Web服務器執行HttpGet請求。它可以在模擬器上正常工作,但不適用於我的HTC Sense。執行只是在沒有任何http請求的情況下結束。任何想法 ?HttpClient不能在真實設備上工作

File f = new File(user.getPhotopath()); 
List<NameValuePair> reqparams = new LinkedList<NameValuePair>(); 
reqparams.add(new BasicNameValuePair("email", user.getEmail())); 
reqparams.add(new BasicNameValuePair("pwd", user.getPassword())); 
reqparams.add(new BasicNameValuePair("name", user.getScreenName())); 
reqparams.add(new BasicNameValuePair("photo", f.getName())); 
reqparams.add(new BasicNameValuePair("preference", user.getPrefs())); 
reqparams.add(new BasicNameValuePair("bluetoothid", bid)); 

String urlstring = "http://www.mysite.com/me?"+ URLEncodedUtils.format(reqparams, "utf-8"); 

try { 
    URL url = new URL(urlstring); 

URI myURI = null; 
try { 
    myURI = url.toURI(); 
} catch (URISyntaxException e) { 
       e.printStackTrace(); 
} 
HttpClient httpClient = new DefaultHttpClient(); 
HttpGet getMethod = new HttpGet(myURI); 
HttpResponse webServerResponse = null; 
HttpEntity httpEntity = null; 
try { 
    webServerResponse = httpClient.execute(getMethod); 
    httpEntity = webServerResponse.getEntity(); 
} catch (ClientProtocolException e) { 
    e.printStackTrace(); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 
if (httpEntity != null) { 

    InputStream instream = httpEntity.getContent(); 
    BufferedReader reader = new BufferedReader(new InputStreamReader(instream)); 
    StringBuilder sb = new StringBuilder(); 
    String line = null; 
    try { 
     while ((line = reader.readLine()) != null) { 
      sb.append(line + "\n"); 
     } 
    } catch (IOException e) { 
      e.printStackTrace(); 
    } finally { 
     try { 
      resultStr = sb.toString(); 
      instream.close(); 
     } catch (IOException e) { 
       e.printStackTrace(); 
     } 
    } 
+0

向我們展示堆棧跟蹤 – Falmarri 2011-02-16 00:43:10

+0

事實上,stacktrace會有幫助,以及您的模擬器是否在代理之後運行。 – ndrix 2011-02-18 20:27:38

回答

0

儘管您的方法是正確的並且可行,但使用EntityUtils幫助程序類以字符串形式檢索響應正文要容易得多。簡單地說:

String body = EntityUtils.toString(httpEntity); 
0

stacktrace中沒有異常或警告。只有內存分配消息。無論如何,我解決了它通過使用URLConnection而不是HttpClient:

try { 
     URL url = new URL(urlstring); 
     URLConnection connection = url.openConnection(); 
     InputStream inputStream = connection.getInputStream(); 
     BufferedInputStream bufferedInput = new BufferedInputStream(inputStream); 

    // Read the response into a byte array 
     ByteArrayBuffer byteArray = new ByteArrayBuffer(50); 
     int current = 0; 
     while((current = bufferedInput.read()) != -1){ 
      byteArray.append((byte)current); 
     } 

     // Construct a String object from the byte array containing the response 
    resultStr = new String(byteArray.toByteArray()); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

由於某種原因,它的工作。仍試圖找出哪裏出了問題。

+0

謝謝大家的答案。 – 2011-02-21 23:06:57

相關問題