尝试使用URLconnection,但出现错误

时间:2018-08-09 19:42:57

标签: android http urlconnection

我正在尝试制作一个使用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();
}

}

1 个答案:

答案 0 :(得分:0)

您无法在主线程上执行IO操作(网络调用)(请参见https://developer.android.com/training/articles/perf-anr

您将需要在后台执行此操作,并更改主线程上的UI。 我建议您使用Retrofit2之类的库。