Search code examples
androidandroid-emulatorhttp-gethtcsense

HttpClient not working on real device


I use this code to do a HttpGet request to my web server. It works fine on emulator but not in my HTC Sense. The excecution just end without doing any http request. Any idea ?

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();
        }
    }

Solution

  • While your approach is correct and will work, it's much easier to use the EntityUtils helper class to retrieve the response body as a string. Simply:

    String body = EntityUtils.toString(httpEntity);