从Android接收错误E / HTTP客户端发送JSON POST请求:http connectionandroid.os.NetworkOnMainThreadException错误

时间:2017-02-08 13:08:14

标签: android json parsing url connection

当我运行我的程序时,它显示错误E / HTTP客户端:httpconnectionandroid.os.NetworkOnMainThreadException中的错误

这是一个包含用户名和密码的简单登录程序。当我单击登录按钮时,它应该在json解析中通过POST方法命中服务器并返回响应成功或失败。

我是Android开发的新手。在这里找出我的错误并解释为什么它没有运行。

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "";
    static EditText username, password;
    Button login;
    String Name, Pass;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        username = (EditText) findViewById(R.id.editText);
        password = (EditText) findViewById(R.id.editText2);
        login = (Button) findViewById(R.id.button);
        login.setOnClickListener(this);
    }
    public String excutePost() throws IOException {
        String url = "website.com/login";
        URL u = new URL(url);
        HttpURLConnection connection = null;
        try{
        connection = (HttpURLConnection) u.openConnection();
        connection.setRequestMethod("POST");

        //set the sending type and receiving type to json
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("Host", "website.com");

        connection.setAllowUserInteraction(false);
        connection.setConnectTimeout(60000);
        connection.setReadTimeout(60000);
        String uname = username.getText().toString();
        String pword = password.getText().toString();

            JSONObject jsonParam = new JSONObject();
            jsonParam.put("userName", uname);
            jsonParam.put("password", pword);
            DataOutputStream printout = new DataOutputStream(connection.getOutputStream ());
            printout.writeBytes(jsonParam.toString());
            printout.flush ();
            printout.close ();
        //Connect to the server
        connection.connect();
        int status = connection.getResponseCode();
        Log.i("HTTP Client", "HTTP status code : " + status);
        switch (status) {
            case 200:
            case 201:
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                bufferedReader.close();
                Log.i("HTTP Client", "Received String : " + sb.toString());
                //return received string
                return sb.toString();
        }

    } catch (MalformedURLException ex) {
        Log.e("HTTP Client", "Error in http connection" + ex.toString());
    } catch (IOException ex) {
        Log.e("HTTP Client", "Error in http connection" + ex.toString());
    } catch (Exception ex) {
        Log.e("HTTP Client", "Error in http connection" + ex.toString());
    } finally {
        if (connection != null) {
            try {
                connection.disconnect();
            } catch (Exception ex) {
                Log.e("HTTP Client", "Error in http connection" + ex.toString());
            }
        }
    }
        return "";
    }
    @Override
    public void onClick(View v) {
        try {
            excutePost();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

请帮助我解决这个问题。

1 个答案:

答案 0 :(得分:0)

只要应用程序尝试在其主线程上进行网络操作(如API调用或Http请求),就会抛出此异常。

在AsyncTask中运行代码:

用户简单线程

Thread thread = new Thread(new Runnable() {

    @Override
    public void run() {
        try  {
            //Your code goes here
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
});

thread.start(); 

不要忘记将其添加到AndroidManifest.xml文件中:

<uses-permission android:name="android.permission.INTERNET"/>