Url,HTTPUrlConnection

Posted 代码改变生活

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Url,HTTPUrlConnection相关的知识,希望对你有一定的参考价值。

package com.cmy.urlcon;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class HttpRequestor {

    private String charset = "utf-8";
    private Integer connectTimeout = null;
    private Integer socketTimeout = null;
    private String proxyHost = null;
    private Integer proxyPort = null;

    public String doGet(String urlPath) throws Exception {

        URL url = new URL(urlPath);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestProperty("Accept-Charset", charset);
        connection.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded");

        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader bfReader = null;
        StringBuffer sb = new StringBuffer();
        String readLine = null;

        if (connection.getResponseCode() >= 300) {
            throw new Exception("HTTP Request is failue, Response code is "
                    + connection.getResponseCode());
        }

        try {
            inputStream = connection.getInputStream();
            inputStreamReader = new InputStreamReader(inputStream);
            bfReader = new BufferedReader(inputStreamReader);
            while ((readLine = bfReader.readLine()) != null) {
                sb.append(readLine);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            bfReader.close();
            inputStreamReader.close();
            inputStream.close();
        }

        return sb.toString();

    }

    public static String doPost(String urlPath, Map paramMap) throws Exception {
        URL url = new URL(urlPath);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        StringBuffer paramBuffer = new StringBuffer();

        if (paramMap != null) {
            Iterator iterator = paramMap.keySet().iterator();
            String key = null;
            String value = null;
            while (iterator.hasNext()) {
                key = (String) iterator.next();

                if ((value = (String) paramMap.get(key)) != null) {
                    paramBuffer.append(value);
                } else {
                    value = "";
                }
                paramBuffer.append(key).append("=").append(value);
                if (iterator.hasNext()) {
                    paramBuffer.append("&");
                }
            }
        }
        System.out.println("POST parameter: " + paramBuffer.toString());

        con.setRequestProperty("Accept-Charset", "utf-8");
        con.setRequestProperty("Content-Type",
                "application/x-www-form-urlencoded");
        con.setConnectTimeout(3000);
        con.setDoInput(true);
        con.setDoOutput(true);
        con.setUseCaches(false);
        String cookie0 = con.getHeaderField("Set-Cookie");

        OutputStream outputStream = null;
        OutputStreamWriter outputStreamWriter = null;
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader bfReader = null;
        StringBuffer sb = new StringBuffer();
        String readLine = null;

        try {
            outputStream = con.getOutputStream();
            outputStreamWriter = new OutputStreamWriter(outputStream);
            outputStreamWriter.write(paramBuffer.toString());
            outputStreamWriter.flush();

        } catch (Exception e) {
            e.printStackTrace();
        }

        if (con.getResponseCode() >= 300) {
            throw new Exception("HTTP Request is failue, Response code is "
                    + con.getResponseCode());
        }

        try {
            inputStream = con.getInputStream();
            inputStreamReader = new InputStreamReader(inputStream);
            bfReader = new BufferedReader(inputStreamReader);
            while ((readLine = bfReader.readLine()) != null) {
                sb.append(readLine);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            outputStreamWriter.close();
            outputStream.close();
            bfReader.close();
            inputStreamReader.close();
            inputStream.close();
        }

        return sb.toString();
    }

    private HttpURLConnection openConnection(URL localURL) throws IOException {
        HttpURLConnection connection;
        if (proxyHost != null && proxyPort != null) {
            Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort));
            connection = (HttpURLConnection) localURL.openConnection(proxy);
        } else {
            connection = (HttpURLConnection) localURL.openConnection();
        }
        return connection;
    }

    private void renderRequest(HttpURLConnection connection) {

        if (connectTimeout != null) {
            connection.setConnectTimeout(connectTimeout);
        }

        if (socketTimeout != null) {
            connection.setReadTimeout(socketTimeout);
        }

    }
    

    public String getCharset() {
        return charset;
    }

    public void setCharset(String charset) {
        this.charset = charset;
    }

    public Integer getConnectTimeout() {
        return connectTimeout;
    }

    public void setConnectTimeout(Integer connectTimeout) {
        this.connectTimeout = connectTimeout;
    }

    public Integer getSocketTimeout() {
        return socketTimeout;
    }

    public void setSocketTimeout(Integer socketTimeout) {
        this.socketTimeout = socketTimeout;
    }

    public String getProxyHost() {
        return proxyHost;
    }

    public void setProxyHost(String proxyHost) {
        this.proxyHost = proxyHost;
    }

    public Integer getProxyPort() {
        return proxyPort;
    }

    public void setProxyPort(Integer proxyPort) {
        this.proxyPort = proxyPort;
    }
    
    /**
     * test case 
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception {
        /* Post Request */
        Map dataMap = new HashMap();
        dataMap.put("username", "Nick Huang");
        dataMap.put("blog", "IT");
        System.out.println(new HttpRequestor().doPost("http://localhost:8080/OneHttpServer/", dataMap));
        
        /* Get Request */
        System.out.println(new HttpRequestor().doGet("http://localhost:8080/OneHttpServer/"));

    }

}

 

以上是关于Url,HTTPUrlConnection的主要内容,如果未能解决你的问题,请参考以下文章

HttpURLConnection超时设置

HttpURLConnection c = URL.openConnection(); c.setRequestProperty() 不起作用

HttpURLConnection获取数据

java调用Http请求 -HttpURLConnection学习

Android之HttpURLConnection

HttpURLConnection 抛出异常 [重复]