Java HTTP Get doGet(String theURL, Map nameValuePairs)

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

Description

do Get

License

Open Source License

Declaration

public static String doGet(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 doGet(String theURL, Map nameValuePairs) throws Exception {
        String request = validateURL(theURL);

        if (nameValuePairs != null && nameValuePairs.size() > 0) {
            if (!request.endsWith("?"))
                request += "?";
            request += encodeParams(nameValuePairs);
        }//w ww . j av a2s .c o m

        URL url = new URL(request);
        URLConnection conn = url.openConnection();

        getRequest(conn);
        return readResponse(conn);
    }

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

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

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

        conn.setDoOutput(true);
        conn.connect();
    }

    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 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. doGET(HttpURLConnection conn)
  2. doGet(String url)
  3. doGet(String url, HashMap params)
  4. doGet(String urlStr)
  5. doGet(String urlString)