Java URL Post postRequest(URLConnection conn, Map nameValuePairs)

Here you can find the source of postRequest(URLConnection conn, Map nameValuePairs)

Description

post Request

License

Open Source License

Declaration

private static void postRequest(URLConnection conn, 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 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" };

    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();/*from  w w w .ja  v  a 2 s  .  co m*/
        }
    }

    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();
    }
}

Related

  1. post(String urlstr, String[] params)
  2. post(String urlString, HashMap values)
  3. postData(String urlStr, String data)
  4. postData(URL base, String urlAddress, Map data)
  5. postForString(URL url, String data)
  6. postToUrl(String page)
  7. postUrl(URL url, String data)
  8. writePostRequest(URLConnection connection, String postRequestBody, String contentType)
  9. writeString(URLConnection connection, String string)