如何在Android Studio中执行HTTP POST请求?

时间:2017-08-28 05:26:09

标签: java android http-post

我正在尝试在这样的Android工作室中执行POST请求。

 btnSignin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {


            //submitForm();
            tryLogin("test@test.com", "Test1234");
        }
    });





protected void tryLogin(String mUsername, String mPassword)
 {
    HttpURLConnection connection;
    OutputStreamWriter request = null;

    URL url = null;
    String response = null;
    String parameters = "email="+mUsername+"&password="+mPassword;
    StrictMode.ThreadPolicy policy = new 
    StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);

    try
    {
        url = new URL("URL");
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestMethod("POST");

        request = new OutputStreamWriter(connection.getOutputStream());
        request.write(parameters);
        request.flush();
        request.close();
        String line = "";
        InputStreamReader isr = new InputStreamReader(connection.getInputStream());
        BufferedReader reader = new BufferedReader(isr);
        StringBuilder sb = new StringBuilder();
        while ((line = reader.readLine()) != null)
        {
            sb.append(line + "\n");
        }
        // Response from server after login process will be stored in response variable.
        response = sb.toString();
        // You can perform UI operations here
        Toast.makeText(this,"Message from Server: \n"+ response, 0).show();
        isr.close();
        reader.close();

    }
    catch(IOException e)
    {
        // Error
    }

但是应用程序崩溃了,我得到了这样的错误 -

  

致命的例外:主要

     

过程:测试,PID:19928

     

android.os.NetworkOnMainThreadException at   android.os.StrictMode $ AndroidBlockGuardPolicy.onNetwork(StrictMode.java:>1425)

     

at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:102)

我在清单文件中添加了互联网权限。 这是因为我没有通过AsyncTask完成它吗? 我怎样才能解决这个问题?

1 个答案:

答案 0 :(得分:-1)

您可以将您的网络操作放在此线程中,或使用asynctask或任何其他库

new Thread(new Runnable() { 
            public void run(){        
            txt1.setText("Thread!!");
            }
        }).start();