Android HttpGet android.os.NetworkOnMainThreadException(Android HttpGet android.os.NetworkOnMainThreadException)

215 IT屋

Im having trouble running the HttpGet, I can access the site with the broswer of the emulator, but when I try to run my application I get these errors.

12-15 05:34:20.573    1702-1702/com.albertoortega.flordemaria E/AndroidRuntime﹕ FATAL EXCEPTION: main
    android.os.NetworkOnMainThreadException
            at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
            at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
            at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
            at libcore.io.IoBridge.connect(IoBridge.java:112)
            at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
            at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
            at java.net.Socket.connect(Socket.java:842)
            at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
            at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
            at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
            at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
            at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
            at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
            at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
            at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
            at com.albertoortega.flordemaria.Objects.JSONParser.makeHttpRequest(JSONParser.java:65)
            at com.albertoortega.flordemaria.ActivityLogin$GetLogin$1.run(ActivityLogin.java:98)
            at android.os.Handler.handleCallback(Handler.java:725)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:5041)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
            at dalvik.system.NativeStart.main(Native Method)

Here's the actual code.

new GetLogin().execute();

class GetLogin extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(ActivityLogin.this);
            pDialog.setMessage("Iniciando Sesion. Porfavor espera...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

        protected String doInBackground(String... params) {
            runOnUiThread(new Runnable() {
                public void run() {
                    int success;
                    try {
                        List<NameValuePair> params = new ArrayList<NameValuePair>();
                        params.add(new BasicNameValuePair(TAG_USERNAME, user));
                        params.add(new BasicNameValuePair(TAG_PASSWORD, pass));

                        JSONObject json = jsonParser.makeHttpRequest(url_login, "GET", params);

                        Log.d("Login", json.toString());

                        success = json.getInt(TAG_SUCCESS);
                        if (success == 1) {
                            JSONArray jsonArray = json.getJSONArray(TAG_OBJECT);
                            JSONObject jsonObject = jsonArray.getJSONObject(0);

                            user = jsonObject.getString(TAG_USERNAME);
                            pass = jsonObject.getString(TAG_PASSWORD);
                            accs = jsonObject.getString(TAG_ACCESS);
                        }else{
                            Toast.makeText(ActivityLogin.this, json.getString(TAG_MESSAGE), Toast.LENGTH_LONG).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });

            return null;
        }

        protected void onPostExecute(String file_url) {
            pDialog.dismiss();
        }
    }

And the class JSONParser

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) {

        // Making HTTP request
        try {

            // check for request method
            if(method == "POST"){
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            }else if(method == "GET"){
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}
解决方案

Exception is clear from the Logs.

Remove "runOnUiThread" from doInBackground().

Network operations must be done in the Background Thread.

我在运行HttpGet时遇到问题,我可以使用模拟器的浏览器
访问该站点,但是当我尝试运行我的应用程序时,会出现这些错误。



  12-15 05:34:20.573 1702-1702 / com.albertoortega.flordemaria E / AndroidRuntime:致命异常:main 
android.os.NetworkOnMainThreadException
在android.os.StrictMode $ AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
在libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
在libcore.io.IoBridge.connectErrno( IoBridge.java:127)libcore.io.IoBridge.connect(IoBridge.java:112)
在java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
在java.net .net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
在java.net.Socket.connect(Socket.java:842)
在org.apache.http.conn.scheme.PlainSocketFactory.connectSocket (PlainSocketFactory.java:119)
在org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
在org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
在org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
在org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
在com.albertoortega.flordemaria.Objects.JSONParser.makeHttpRequest(JSONParser.java:65)
在com。 albertoortega.flordemaria.ActivityLogin $ GetLogin $ 1.run(ActivityLogin.java:98)
在android.os.Handler.handl eCallback(Handler.java:725)
在android.os.Handler.dispatchMessage(Handler.java:92)
在android.os.Looper.loop(Looper.java:137)
在android.app.ActivityThread.main(ActivityThread.java:5041)处
在java.lang.reflect.Method.invokeNative(本机方法)在
处在java.lang.reflect.Method.invoke(方法。 java:511)com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:793)
com.android.internal.os.ZygoteInit.main(ZygoteInit.java: 560)
在dalvik.system.NativeStart.main(本机方法)




  new GetLogin()。execute(); 

类GetLogin扩展了AsyncTask< String,String,String> {

@Override
protected void onPreExecute(){
super.onPreExecute();
pDialog = new ProgressDialog(ActivityLogin.this);
pDialog.setMessage( Iniciando Sesion。Porfavor espera ...);
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}

受保护的字符串doInBackground(String ... params){
runOnUiThread(new Runnable(){
public void run(){
int成功;
尝试{
List< NameValuePair>参数= new ArrayList< NameValuePair>();
params.add(new BasicNameValuePair(TAG_USERNAME,用户));
params.add (new BasicNameValuePair(TAG_PASSWORD,pass));

JSONObject json = jsonParser.makeHttpRequest(url_login, GET,params);

Log.d( Login, json.toString());

success = json.getInt(TAG_SUCCESS);
if(success == 1){
JSONArray jsonArray = json.getJSONArray(TAG_OBJECT);
JSONObject jsonObject = jsonArray.getJSONObject(0);

用户= jsonObject.getString(TAG_USERNAME);
pass = jsonObject.getString(TAG_PASSWORD);
accs = jsonObject.getString(TAG_ACCESS);
} else {
Toast.makeText(ActivityLogin.this,json.getString(TAG_MESSAGE),Toast.LENGTH_LONG).show();
}
} catch(JSONException e){
e.printStackTrace();
}
}
});

返回null;
}

保护无效onPostExecute(String file_url){
pDialog.dismiss();
}
}


和JSONParser类



 公共类JSONParser {

static InputStream为= null;
静态JSONObject jObj = null;
static String json =;

//构造函数
public JSONParser(){

}

//函数从url
中获取json //通过使HTTP POST或GET方法
成为公共JSONObject makeHttpRequest(String url,String method,List< NameValuePair>参数){

//使HTTP请求
尝试{

//检查请求方法
if(method == POST){
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost =新的HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));

HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
是= httpEntity.getContent();

}否则if(method == GET){
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, utf-8);
url + =? + paramString;
HttpGet httpGet =新的HttpGet(url);

HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
是= httpEntity.getContent();
}

} catch(UnsupportedEncodingException e){
e.printStackTrace();
} catch(ClientProtocolException e){
e.printStackTrace();
} catch(IOException e){
e.printStackTrace();
}

试试{
BufferedReader reader = new BufferedReader(new InputStreamReader(is, iso-8859-1),8);
StringBuilder sb = new StringBuilder();
字符串行= null;
while((line = reader.readLine())!= null){
sb.append(line + \n);
}
is.close();
json = sb.toString();
} catch(Exception e){
Log.e( Buffer Error,转换结果时出错 + e.toString());
}

//尝试将字符串解析为JSON对象
try {
jObj = new JSONObject(json);
} catch(JSONException e){
Log.e( JSON Parser,解析数据时出错 + e.toString());
}

//返回JSON字符串
return jObj;

}
}

解决方案

从日志中清除异常。



从 doInBackground删除 runOnUiThread ()。



网络操作必须在后台线程中完成。


本文地址:IT屋 » Android HttpGet android.os.NetworkOnMainThreadException