do Http Post - Java Network

Java examples for Network:Http

Description

do Http Post

Demo Code


//package com.java2s;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class Main {
    public static void main(String[] argv) throws Exception {
        String url = "java2s.com";
        String request = "java2s.com";
        System.out.println(doHttpPost(url, request));
    }// w ww. ja v a 2s  .  c  om

    public static String doHttpPost(String url, String request)
            throws MalformedURLException, IOException {
        // establish connection and send request
        HttpURLConnection connection = (HttpURLConnection) new URL(url)
                .openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Length",
                String.valueOf(request.length()));
        connection.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded");
        connection.setDoOutput(true);
        connection.setDoInput(true);

        // write request
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
                connection.getOutputStream()));
        writer.write(request);
        writer.flush();

        // read response
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                connection.getInputStream()));
        String line, content = "";
        while ((line = reader.readLine()) != null) {
            content = content + line + "\n";
        }
        return content;
    }
}

Related Tutorials