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/"));

    }

}
时间: 2024-10-03 02:58:07

Url,HTTPUrlConnection(一)的相关文章

Android代码(Handler的运用),HttpURLConnection的应用,将url图片地址转换成图片。

?? 1 布局文件, <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:

Android网络:HTTP之利用HttpURLConnection访问网页、获取网络图片实例 (附源码)

http://blog.csdn.net/yanzi1225627/article/details/22222735 如前文所示的TCP局域网传送东西,除了对传输层的TCP/UDP支持良好外,Android对HTTP(超文本传输协议)也提供了很好的支持,这里包括两种接口: 1.标准Java接口(java.net) ----HttpURLConnection,可以实现简单的基于URL请求.响应功能: 2.Apache接口(org.appache.http)----HttpClient,使用起来更方

Android利用HttpURLConnection实现模拟登录

最近在做一个APP,需要模拟登录教务处,之前曾经用HttpClient做过,点这里,但是发现最新的Android SDK已经不支持Httpclient了,所以只好在琢磨一下HttpURLConnection实现了,其中一个问题浪费了不少时间,下面这行代码一旦添加就无法登录: httpURLConnection.setRequestProperty("Content-Type","text/html; charset=GBK"); 贴一下效果,由于是实现模拟登录,就没

10_Android中通过HttpUrlConnection访问网络,Handler和多线程使用,读取网络html代码并显示在界面上,ScrollView组件的使用

?? 编写如下项目: 2 编写Android清单文件 <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.itheima28.htmldemo" android:versionCode="1" andr

HttpURLConnection中connection.getInputStream()报异常FileNotFoundException

============问题描述============ 在AVD上测试没问题.换到设备上时报FileNotFound的异常,经常报这个异常.各位帮忙看看. 代码如下: public class HttpAssist {          public static String doPost(JSONObject json) throws IOException{         URL postUrl = new URL(Config.url);         HttpURLConnect

HttpURLConnection传JSON数据

try { //创建连接 URL url = new URL(url); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setUseCaches(false); connect

利用HttpURLConnection发送请求

HttpURLConnection: 每个 HttpURLConnection实例都可用于生成单个请求,但是其他实例可以透明地共享连接到 HTTP 服务器的基础网络.请求后在 HttpURLConnection 的 InputStream 或 OutputStream 上调用 close() 方法可以释放与此实例关联的网络资源,但对共享的持久连接没有任何影响.如果在调用 disconnect() 时持久连接空闲,则可能关闭基础套接字 HttpURLConnection的父类是URLConnect

HttpUrlConnection 基础使用

From https://developer.android.com/reference/java/net/HttpURLConnection.html HttpUrlConnection: A URLConnection with support for HTTP-specific features. See the specfor details. Uses of this class follow a pattern: Obtain a new HttpURLConnection by c

HttpURLConnection 数据请求+Gson解析,Listview展示

import java.io.IOException;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import java.util.ArrayList;import java.util.List; import com.google.gson.Gson; import android.os.Bundle;