尝试使用 URLconnection 但出现错误

trying to use URLconnection but I get errors

我正在尝试创建一个项目,使用 post 方法向 php 页面发送和接收数据。我在网上找到了这段代码,但我无法解决它的错误。

您可以在下图中看到错误: the errors

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //make message text field object
    EditText msgTextField = (EditText) findViewById(R.id.editText);
    //make button object
    Button sendButton = (Button) findViewById(R.id.b);

    URL url = null;
    try {
        url = new URL("http://yoururl.com");
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
    conn.setReadTimeout(10000);
    conn.setConnectTimeout(15000);
    try {
        conn.setRequestMethod("POST");
    } catch (ProtocolException e) {
        e.printStackTrace();
    }
    conn.setDoInput(true);
    conn.setDoOutput(true);

    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("firstParam", paramValue1));
    params.add(new BasicNameValuePair("secondParam", paramValue2));
    params.add(new BasicNameValuePair("thirdParam", paramValue3));

    OutputStream os = conn.getOutputStream();
    BufferedWriter writer = new BufferedWriter(
            new OutputStreamWriter(os, "UTF-8"));
    writer.write(getQuery(params));
    writer.flush();
    writer.close();
    os.close();

    conn.connect();
}

}

不能在主线程上做IO操作(网络调用)(见https://developer.android.com/training/articles/perf-anr

您需要在后台执行此操作并在主线程上更改 UI。 我建议你使用一些像 Retrofit2.

这样的库