我没有设法从android模拟器查询Web服务(之前我有一个UnresolvedHostException,但这没关系)。现在我可以继续了,我在HttpResponse的实体中没有返回任何内容(长度为-1)。
String url = serverUrl + resource;
Log.d(TAG, "GET: " + url);
HttpClient client = new DefaultHttpClient();
HttpGet getMethod = new HttpGet((url));
getMethod.setHeader("User-Agent", USER_AGENT);
getMethod.addHeader("Authorization", "Basic " + getCredentials());
HttpResponse httpResponse = client.execute(getMethod);
Log.e(TAG, "RESPONSE:" + httpResponse);
Log.i(TAG,httpResponse.getStatusLine().toString());
Log.i(TAG + "1",httpResponse.getLocale().toString());
Log.i(TAG + "2",httpResponse.getHeaders(USER_AGENT).toString());
Log.i(TAG + "3",httpResponse.getEntity().toString());
Log.i(TAG + "4",httpResponse.getEntity().getContent().toString());
int length = (int) httpResponse.getEntity().getContentLength();
Log.e(TAG + "5", "LENGTH:" + length);
日志:
D/HttpServices( 275): GET: http://www.google.com/search?q=android
D/dalvikvm( 275): GC freed 2992 objects / 217016 bytes in 103ms
E/HttpServices( 275): RESPONSE:org.apache.http.message.BasicHttpResponse@43ca4920
I/HttpServices( 275): HTTP/1.1 200 OK
I/HttpServices1( 275): en_US
I/HttpServices2( 275): [Lorg.apache.http.Header;@43c44e10
I/HttpServices3( 275): org.apache.http.conn.BasicManagedEntity@43c40be8
I/HttpServices4( 275): org.apache.http.conn.EofSensorInputStream@43c51c60
E/HttpServices5( 275): LENGTH:-1
我不在代理后面,并在清单中添加了INTERNET权限。 不检索获取查询(http://www.google.com/search?q=android)内容的原因可能是什么。 非常感谢你的帮助, LUC
答案 0 :(得分:4)
不要依赖内容长度。 有时它无法找到内容长度 只需检索返回的数据
URL url = new URL("xyz.com";);
URLConnection conn = url.openConnection();
conn.setRequestProperty("Authorization", "Basic"+getcredentials());
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
//read d response till d end
while ((line = rd.readLine()) != null) {//process the line response}