[英]Problem with HTTP Post in Android
我在Android上進行HTTP POST時遇到問題。
代碼讀取響應時會發生問題,它無法獲取我要檢索的完整網頁代碼。
我只檢索了一部分網頁。
這是代碼:
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("text", "06092010"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response;
response=httpclient.execute(httppost);
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String s = "";
String line = reader.readLine();
while(line != null){
s += line+"\n";
line = reader.readLine();
}
Log.d("Street", "Result: "+s);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
Log.d("Street", e.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
Log.d("Street", e.toString());
} catch (Exception e) {
Log.d("Street", e.toString());
}
因此,在您到達流的末尾之前,reader.readLine返回null? 緩沖區末尾是否包含換行符? 文檔建議流的末尾不構成“行尾”:
閱讀一行文字。 一行被認為由換行符('\\ n'),回車符('\\ r')或回車符后緊跟換行符之一終止。
我自己使用了這種方法,它可以工作,但不是一個非常有效的解決方案:
public static String URLToString(URL url) throws IOException {
InputStream in = (InputStream) url.getContent();
int ch;
StringBuffer b = new StringBuffer();
while( ( ch = in.read() ) != -1 ){
b.append( (char)ch );
}
return b.toString();
}
使用您的代碼,我得到相同的結果,但是現在我知道了問題所在。
問題不是代碼,而是我打印結果字符串的Android LogCat(一個Logger)。 在此記錄器中,如果字符串太長,則僅顯示一小部分結果。
所以問題是android的記錄器顯示long字符串的方式
感謝Gaz的幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.