user3329118
user3329118

Reputation: 27

Android - openConnection giving error

I have tried as much as I could yet my code maintains errors. I am simply trying to do a POST method in an android app. I do realize in the code below you will find void with capital "v" this is because the error wasn't going till I made it as Void

public class PostMethod extends AsyncTask<URL, Void, Void> {


    protected Void doInBackground(URL... url) {


        try {

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(10000);
            conn.setConnectTimeout(15000);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
            wr.writeBytes("Hello! ");
            wr.flush();
            wr.close();

        } catch (Exception e) {
            System.out.println("Error! ");
        }


    }

}

This code is placed in my on create function.

try {
    new PostMethod().execute(new URL("http://posttestserver.com/data/"));
} catch (MalformedURLException e) {
    e.printStackTrace();
}

Current error: It cannot identify openConnection()

Upvotes: 0

Views: 999

Answers (1)

ρяσѕρєя K
ρяσѕρєя K

Reputation: 132982

use

HttpURLConnection conn = (HttpURLConnection) url[0].openConnection();

instead of

 HttpURLConnection conn = (HttpURLConnection) url.openConnection();

beacuse doInBackground parameter is Varargs method argument

Upvotes: 1

Related Questions