post Xml to URL by encoding - Android Network

Android examples for Network:HTTP Post

Description

post Xml to URL by encoding

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[] postXml(String path, String xml, String encoding)
            throws Exception {
        byte[] data = xml.getBytes(encoding);
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);/*from   www  . j  a v  a 2s  .c  o m*/
        conn.setRequestProperty("Content-Type", "text/xml; charset="
                + encoding);
        conn.setRequestProperty("Content-Length",
                String.valueOf(data.length));
        conn.setConnectTimeout(5 * 1000);
        OutputStream outStream = conn.getOutputStream();
        outStream.write(data);
        outStream.flush();
        outStream.close();
        if (conn.getResponseCode() == 200) {
            return read2Byte(conn.getInputStream());
        }
        return null;
    }

    public static byte[] read2Byte(InputStream inStream) throws Exception {
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outSteam.write(buffer, 0, len);
        }
        outSteam.close();
        inStream.close();
        return outSteam.toByteArray();
    }
}

Related Tutorials