Java HTTP Post doPost(String theURL, Map nameValuePairs)

Here you can find the source of doPost(String theURL, Map nameValuePairs)

Description

do Post

License

Open Source License

Declaration

public static String doPost(String theURL, Map nameValuePairs) throws Exception 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.io.*;
import java.net.*;
import java.util.*;

public class Main {
    public static boolean printHeaders = false;
    public static boolean useStdHeaders = false;
    static final String stdReqHdr[] = {
            //      "Connection", "Keep-Alive",
            "User-Agent", "Mozilla/4.5 [en] (X11; U; SunOS 5.6 sun4u)", "Accept",
            "image/gif, image/x-xbitmap, image/jpeg," + "image/pjpeg, image/png, */*", "Accept-Encoding", "gzip",
            "Accept-Language", "en", "Accept-Charset", "iso-8859-1,*,utf-8" };

    public static String doPost(String theURL, Map nameValuePairs) throws Exception {
        URL url = new URL(validateURL(theURL));
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);//from  w ww .j  av a2s. co m

        postRequest(conn, nameValuePairs);
        return readResponse(conn);
    }

    public static String validateURL(String url) {
        if (!url.startsWith("http://"))
            return "http://" + url;
        else
            return url;
    }

    private static void postRequest(URLConnection conn, Map nameValuePairs) throws Exception {
        if (nameValuePairs != null) {
            if (useStdHeaders)
                for (int i = 0; i < stdReqHdr.length - 1; i++)
                    conn.setRequestProperty(stdReqHdr[i], stdReqHdr[i + 1]);

            PrintWriter out = new PrintWriter(conn.getOutputStream());

            out.print(encodeParams(nameValuePairs));
            out.close();
        }
    }

    public static String readResponse(URLConnection conn) throws Exception {
        BufferedReader in;
        StringBuffer response = new StringBuffer();
        String line;

        try {
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        } catch (Exception ex) {
            InputStream err = ((HttpURLConnection) conn).getErrorStream();
            if (err == null) {
                System.err.println("Headers: " + getResponseHeaders(conn));
                throw ex;
            }
            in = new BufferedReader(new InputStreamReader(err));
        }

        if (printHeaders)
            response.append(getResponseHeaders(conn));

        while ((line = in.readLine()) != null)
            response.append(line + "\n");

        in.close();

        return response.toString();
    }

    public static String encodeParams(Map nameValuePairs) {
        StringBuffer params = new StringBuffer();
        Iterator nvp = nameValuePairs.keySet().iterator();
        String name, value;
        char ch;

        while (nvp.hasNext()) {
            name = (String) nvp.next();
            value = (String) nameValuePairs.get(name);
            if (value == null)
                value = "null";
            if (nvp.hasNext())
                ch = '&';
            else
                ch = '\n';
            params.append(name + "=" + URLEncoder.encode(value) + ch);
        }

        return params.toString();
    }

    public static String getResponseHeaders(URLConnection conn) {
        StringBuffer headers = new StringBuffer();
        String key;
        int n = 1;

        headers.append("\n----------\n");
        while ((key = conn.getHeaderFieldKey(n)) != null) {
            String value = conn.getHeaderField(n);
            headers.append(key + ": " + value + "\n");
            n++;
        }

        headers.append("----------\n");
        return headers.toString();
    }
}

Related

  1. doHttpPost(URL url, String requestBody)
  2. doPOST(HttpURLConnection conn, InputStream input)
  3. doPost(String targetURL, String urlParameters, String contentType)
  4. doPost(URL url, String body, String... args)
  5. executePost(String url, JSONObject data)
  6. executePostWithCredentials(String targetURL, String urlParameters, String userName, String password)
  7. getHttpPOSTConnection(String urlStr, String charSet, Map props, Map params)