Url,HTTPUrlConnection(一)

來源:互聯網
上載者:User

標籤:finally   imp   exception   close   new   utf-8   ons   null   get   

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(一)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.