do HTTP Post Request - Android Network

Android examples for Network:HTTP Request

Description

do HTTP Post Request

Demo Code


//package com.java2s;

import java.io.ByteArrayOutputStream;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;

import java.net.URL;

public class Main {
    public static byte[] doPostRequest(String urlString, String params) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        InputStream is = null;// ww  w .  ja v a 2  s.  c o m
        byte[] result = null;
        URL url = null;
        HttpURLConnection connection = null;
        OutputStream out = null;
        StringBuilder sb = new StringBuilder();

        byte[] entity = params.getBytes();

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

            connection.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");
            connection.setRequestProperty("Content-Length", entity.length
                    + "");

            OutputStream outputStream = connection.getOutputStream();
            outputStream.write(entity);
            outputStream.flush();
            outputStream.close();

            if (connection.getResponseCode() == 200) {
                is = connection.getInputStream();
                byte[] buffer = new byte[1024];
                int length = 0;

                while ((length = is.read(buffer)) != -1) {
                    baos.write(buffer, 0, length);
                    baos.flush();
                }

                result = baos.toByteArray();
            }

        } catch (Exception e) {

        } finally {
            try {
                if (connection != null) {
                    connection.disconnect();
                }

                if (baos != null) {
                    baos.close();
                }

                if (is != null) {
                    is.close();
                }

            } catch (Exception e) {

            }
        }

        return result;
    }
}

Related Tutorials