Java HTTP Post postURL(final URL url, final String request)

Here you can find the source of postURL(final URL url, final String request)

Description

post URL

License

Open Source License

Declaration

public static String postURL(final URL url, final String request) throws IOException 

Method Source Code


//package com.java2s;
// Use and redistribution of this file is governed by the license terms in

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

public class Main {
    private static String FF_UA = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.4) Gecko/2008111317 Ubuntu/8.04 (hardy) Firefox/3.0.4";

    public static String postURL(final URL url, final String request) throws IOException {
        final HttpURLConnection conn = connect(url, true);
        final OutputStreamWriter out = new OutputStreamWriter(conn.getOutputStream());
        out.write(request);//from  w ww .ja  v  a  2  s . c  o  m
        out.close();
        final StringBuilder content = new StringBuilder();
        final InputStreamReader in = new InputStreamReader(conn.getInputStream(), "UTF-8");
        final char[] buff = new char[1024];
        while (true) {
            final int blen = in.read(buff);
            if (blen < 0) {
                break;
            }
            content.append(buff, 0, blen);
        }
        in.close();
        conn.disconnect();
        return content.toString();
    }

    public static HttpURLConnection connect(final URL url, final boolean output) throws IOException {
        final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("User-Agent", FF_UA);
        conn.setConnectTimeout(10000); // 10 seconds is reasonable
        conn.setReadTimeout(5000); // 5 seconds is reasonable
        conn.setDoOutput(output);
        conn.connect();
        return conn;
    }
}

Related

  1. postData(Reader data, URL endpoint, Writer output)
  2. postForm(String url, Map params)
  3. postHTTPQuery(String url, String urlParameters)
  4. postJSON(JSONObject job, HttpURLConnection conn)
  5. postRaw(URL url, String params)
  6. put(String url, String content)
  7. put(URL host, String endpoint, String customer, String name, String version, InputStream in)
  8. putPOST(HttpURLConnection h, String query)
  9. requestPost(final String remoteUrl, final byte[] content)