连接Android应用程序与Web服务器

时间:2014-03-08 10:24:49

标签: java android android-layout mobile networkonmainthread

我的连接代码是从网站获取字符串....

网址值为http://sagindia.netne.net/sendmail.php

public String makeServiceCall(String url) {
    try {
      // http client
      DefaultHttpClient httpClient = new DefaultHttpClient();
      HttpEntity httpEntity = null;
      HttpResponse httpResponse = null;

      HttpGet httpGet = new HttpGet(url);
      httpResponse = httpClient.execute(httpGet);
      httpEntity = httpResponse.getEntity();
      response = EntityUtils.toString(httpEntity);
   } catch (Exception e) {

   }
   return response;
}

在行中显示错误

httpResponse = httpClient.execute(httpGet);

log cat error part ..

03-08 15:46:06.951: E/AndroidRuntime(1004): Caused by: anroid.os.NetworkOnMainThreadException

我已经解决了这个问题,但无法解决这个问题......我是第一次尝试从服务器获得响应....如果有人有解决方案PLZ帮助我..

1 个答案:

答案 0 :(得分:0)

我从@blackTigher提供的链接中得到了答案......

问题是因为主线上的网络......

所以在连接到httpclient之前添加了这段代码

 StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
 StrictMode.setThreadPolicy(policy);

它对我有用......

有关详细信息,请访问NetworkOnMainThreadException