Search code examples
androidhttpurlconnection

trying to use URLconnection but I get errors


I am trying to make a project for sending and recieving data to a php page using post method. I have found this piece of code on the net but I can't solve its errors.

you can see the errors in the image below: 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();
}

}

Solution

  • You can't do IO operations (network call) on the main thread (see https://developer.android.com/training/articles/perf-anr)

    You will need to do this in the background and change the UI on the main thread. I advise you to use some libs like Retrofit2.