Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DefaultHttpClient, HttpPost, etc. deprecated. How to post now?

Tags:

android

Before Android API 22 i simply did the following:

/**
 * 
 * @param url
 * @param params
 * @return
 * @throws ClientProtocolException
 * @throws IOException
 */
public InputStream getStreamFromConnection(String url, List<NameValuePair> params) throws ClientProtocolException, IOException {
    if(ConnectionDetector.isConnectedToInternet(this.context)) {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(new UrlEncodedFormEntity(params, "utf-8"));

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();

        return httpEntity.getContent();
    } else {
        return null;
    }
}

Nearly everything in the above code now is deprecated (NameValuePair, DefaultHttpClient, HttpPost, UrlEncodedFormEntity, HttpResponse, HttpEntity, ClientProtocolException) and i cant find a recommend way to do in API 22+. How should i do my post now?

like image 491
Mulgard Avatar asked Dec 19 '22 01:12

Mulgard


2 Answers

You can use HttpURLConnection now, you can find complete description at below link:

http://developer.android.com/reference/java/net/HttpURLConnection.html

like image 125
Aakash Avatar answered May 20 '23 11:05

Aakash


this is an example for async task with POST method:

private class SendMessageTask extends AsyncTask<String, Void, String> {

    Graduate targetGraduate;

    public SendMessageTask(Graduate targetGraduate){
        this.targetGraduate = targetGraduate;

    }

    @Override
    protected String doInBackground(String... params) {
        URL myUrl = null;
        HttpURLConnection conn = null;
        String response = "";
        String data = params[0];

        try {
            myUrl = new URL("http://your url");
            conn = (HttpURLConnection) myUrl.openConnection();
            conn.setReadTimeout(10000);
            conn.setConnectTimeout(15000);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);

            //one long string, first encode is the key to get the  data on your web 
            //page, second encode is the value, keep concatenating key and value.
            //theres another ways which easier then this long string in case you are 
            //posting a lot of info, look it up.
            String postData = URLEncoder.encode("TOKEN", "UTF-8") + "=" +
                    URLEncoder.encode(targetGraduate.getToken(), "UTF-8") + "&" +
                    URLEncoder.encode("SENDER_ID", "UTF-8") + "=" +
                    URLEncoder.encode(MainActivity.curretUser.getId(), "UTF-8") + "&" +
                    URLEncoder.encode("MESSAGE_DATA", "UTF-8") + "=" +
                    URLEncoder.encode(data, "UTF-8");
            OutputStream os = conn.getOutputStream();

            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
            bufferedWriter.write(postData);
            bufferedWriter.flush();
            bufferedWriter.close();

            InputStream inputStream = conn.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
            String line = "";
            while ((line = bufferedReader.readLine()) != null) {
                response += line;
            }
            bufferedReader.close();
            inputStream.close();
            conn.disconnect();
            os.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return response;
    }

    @Override
    protected void onPostExecute(String s) {
        //do what ever you want with the response
        Log.d("roee", s);
    }
}
like image 43
Roee Avatar answered May 20 '23 10:05

Roee