As many of you know new apps should use HttpUrlconnection because Httpclient will not work past api 22. I have below code in HttpClient that successfully posts to the server and then I comment that out and swap in HttpUrlconnection and it does not post. What could possibly be wrong with my code for HttpUrlconnection
    URL url = new URL(LOGIN_URL);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.connect();
        conn.setReadTimeout(10000);
        conn.setConnectTimeout(15000);
        conn.setRequestMethod("POST");
       String cert="username=user_777&password=76566";
        conn.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(conn.getOutputStream());
        wr.writeBytes(cert);
        wr.flush();
        wr.close();
      conn.disconnect();
This similar code in HttpClient works perfectly
 HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(LOGIN_URL);
        List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
        nameValuePair.add(new BasicNameValuePair("username", "test_user"));
        nameValuePair.add(new BasicNameValuePair("password", "123456789"));
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
        HttpResponse response = httpClient.execute(httpPost);
        Log.d("Http Post Response:", response.toString());
Httpclient works, HttpUrlclient does not how can I make it work? They both have the same URL.
 
                        
The problem is that you're calling
conn.setDoOutput(true)when the connection is already open.From the documentation:
Moving the call to
conn.setDoOutput(true);to beforeconn.connect();fixed the issue.Here is the error that I got with your original code:
Here is fully working and tested code, note I added some try/catch blocks and moved things around a bit, and also added code to read the result from the server: