我使用此代码对我的Web服务器执行HttpGet请求。它在模拟器上工作正常但在我的HTC Sense中没有。执行只是在没有做任何http请求的情况下结束。有什么想法吗?
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 :(得分: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();
}
出于某种原因,它有效。还在试图弄清楚出了什么问题。
答案 1 :(得分:0)
虽然您的方法是正确的并且可行,但使用EntityUtils帮助程序类以字符串形式检索响应主体要容易得多。简单地:
String body = EntityUtils.toString(httpEntity);