DefaultHttpClient, HttpPost, etc. Outdated. How to send a message?

Before Android API 22, I just 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;
    }
}

Almost all of the above code is now out of date ( NameValuePair, DefaultHttpClient, HttpPost, UrlEncodedFormEntity, HttpResponse, HttpEntity, ClientProtocolException), and I can not find the recommended way to do API 22+. How do I make my post now?

+4
source share
4 answers

Now you can use HttpURLConnection, you can find the full description at the link below:

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

+5
source

This is an example of an async task with the 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);
    }
}
+4
source

Hashmap List. :

HashMap<String,String> contact=new HashMap<>();
contact.put("name",name);
contact.put("address",add);

try{
    URL url=new URL(strURL);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setDoInput(true);
    conn.setDoOutput(true);

    OutputStream os = conn.getOutputStream();
    BufferedWriter writer = new BufferedWriter(
                        new OutputStreamWriter(os, "UTF-8"));
    writer.write(postDataStr(contact));

    writer.flush();
    writer.close();
    os.close();

    int responseCode=conn.getResponseCode();
    conn.disconnect();
    if (responseCode == HttpURLConnection.HTTP_OK)
        return "success";
    else
        return "";
}catch (Exception e)
{
    e.printStackTrace();
}

postDataStr() Hashmap , -, . :

private String postDataStr(HashMap<String, String> params) throws UnsupportedEncodingException{
    StringBuilder result = new StringBuilder();
    boolean first = true;
    for(Map.Entry<String, String> entry : params.entrySet()){
        if (first)
            first = false;
        else
            result.append("&");

        result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
        result.append("=");
        result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
    }

    return result.toString();
}
0

Whule, , , , ( ) , , , android. , .. Square Retrofit Volley .

0

All Articles