Java HTTP Header getFromUrl(Map headerMap, URL loc, Proxy proxy)

Here you can find the source of getFromUrl(Map headerMap, URL loc, Proxy proxy)

Description

get From Url

License

Open Source License

Declaration

private static String getFromUrl(Map<String, String> headerMap, URL loc, Proxy proxy) 

Method Source Code


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

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;

import java.net.Proxy;
import java.net.URL;

import java.util.Iterator;
import java.util.Map;

import java.util.zip.GZIPInputStream;
import java.util.zip.Inflater;
import java.util.zip.InflaterInputStream;

public class Main {
    private static String getFromUrl(Map<String, String> headerMap, URL loc, Proxy proxy) {
        String encode = "UTF-8";
        String result = "";
        try {//from ww  w . j  a v a2 s . c  om
            HttpURLConnection urlCon;
            if (proxy == null) {
                urlCon = (HttpURLConnection) loc.openConnection();
            } else {
                urlCon = (HttpURLConnection) loc.openConnection(proxy);
            }
            Iterator<String> header = headerMap.keySet().iterator();
            while (header.hasNext()) {
                String key = (String) header.next();
                urlCon.addRequestProperty(key, headerMap.get(key));
            }
            String cType = urlCon.getHeaderField("Content-Type");
            int i = cType.indexOf("charset=");
            if (i != -1)
                encode = cType.substring(i + 8);
            InputStream input;
            cType = urlCon.getContentEncoding();
            input = new BufferedInputStream(urlCon.getInputStream());
            if (cType != null) {
                if (cType.indexOf("gzip") != -1) {
                    input = new GZIPInputStream(input);
                } else if (cType.indexOf("deflate") != -1) {
                    input = new InflaterInputStream(input, new Inflater(true));
                }
            }
            Reader reader = new InputStreamReader(input, encode);
            while ((i = reader.read()) != -1)
                result += (char) i;
            reader.close();
        } catch (IOException e) {
            System.err.println(e);
        }
        return result;
    }
}

Related

  1. dumpHeaders(HttpURLConnection conn, PrintStream out)
  2. dumpHttpHeaders(HttpURLConnection conn, java.io.PrintStream out)
  3. fillHeaders(HttpURLConnection urlConnection, Map headers)
  4. GET_Stream(String url, HashMap headers)
  5. getConnection(URL url, String method, Map header, String ctype)
  6. getHeaderField(final URL url, final String name)
  7. getHttpResponseHeader(HttpURLConnection http)
  8. getIntFromHeader(HttpURLConnection connection, String headerName)
  9. getLastModifiedHeader(URL url)