java.net.URLConnection

public abstract class URLConnection extends Object

他有2个子类: HttpURLConnection (http请求)和 JarURLConnection (连接到JAR文件)

可以通过这个抽象类的实例, 建立应用程序和URL之间的通讯连接, 从而可以发送请求,获得response.

1 建立连接对象

2 设置请求的属性或附加参数对

3 使用connect()方法, 建立连接

4 调用 各种get方法获取返回的内容体和头信息

实例: 

package com.exodus.weistore.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

public class HttpHelper {
	
	
    /**
     * 发送get请求
     *
     * @param url  请求地址
     * @param list 请求参数
     *
     * @return 请求结果
     *
     * @throws IOException
     */
    public static String sendGet(String url, List<HTTPParam> list)
    		throws IOException {
        StringBuffer buffer = new StringBuffer(); //用来拼接参数
        StringBuffer result = new StringBuffer(); //用来接受返回值
        URL httpUrl = null; //HTTP URL类 用这个类来创建连接
        URLConnection connection = null; //创建的http连接
        BufferedReader bufferedReader = null; //接受连接受的参数
        //如果存在参数,我们才需要拼接参数 类似于 localhost/index.html?a=a&b=b
        
        if (list != null && list.size() > 0) 
        {
            for (int i = 0; i < list.size(); i++) 
            {
                buffer.append(list.get(i).getKey()).append("=")
                	.append(URLEncoder.encode(list.get(i).getValue(), "utf-8"));
                //如果不是最后一个参数,不需要添加&
                if ((i + 1) < list.size()) 
                {
                    buffer.append("&");
                }
            }
            url = url + "?" + buffer.toString();
        }
        //创建URL
        httpUrl = new URL(url);
        //建立连接
        connection = httpUrl.openConnection();
        connection.setRequestProperty("accept", 
        	"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        connection.setRequestProperty("connection", "keep-alive");
        connection.setRequestProperty("user-agent", 
        	"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0");
        connection.connect();
        //接受连接返回参数
        bufferedReader = new BufferedReader(
        		new InputStreamReader(connection.getInputStream()));
        String line;
        while ((line = bufferedReader.readLine()) != null) 
        {
            result.append(line);
        }
        bufferedReader.close();
        return result.toString();
    }
 
    /**
     * 发送Post请求
     *
     * @param url  请求地址
     * @param list 请求参数
     *
     * @return 请求结果
     *
     * @throws IOException
     */
    public static String sendPost(String url, List<HTTPParam> list) 
    		throws IOException {
        StringBuffer buffer = new StringBuffer(); //用来拼接参数
        StringBuffer result = new StringBuffer(); //用来接受返回值
        URL httpUrl = null; //HTTP URL类 用这个类来创建连接
        URLConnection connection = null; //创建的http连接
        PrintWriter printWriter = null;
        BufferedReader bufferedReader; //接受连接受的参数
        //创建URL
        httpUrl = new URL(url);
        //建立连接
        connection = httpUrl.openConnection();
        connection.setRequestProperty("accept", 
        	"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        connection.setRequestProperty("connection", "keep-alive");
        connection.setRequestProperty("user-agent", 
        	"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0");
        connection.setDoOutput(true);
        connection.setDoInput(true);
        printWriter = new PrintWriter(connection.getOutputStream());
        if (list != null && list.size() > 0) 
        {
            for (int i = 0; i < list.size(); i++) 
            {
                buffer.append(list.get(i).getKey()).append("=")
                	.append(URLEncoder.encode(list.get(i).getValue(), "utf-8"));
                //如果不是最后一个参数,不需要添加&
                if ((i + 1) < list.size()) 
                {
                    buffer.append("&");
                }
            }
        }
        printWriter.print(buffer.toString());
        printWriter.flush();
        connection.connect();
        //接受连接返回参数
        bufferedReader = new BufferedReader(
        		new InputStreamReader(connection.getInputStream()));
        String line;
        while ((line = bufferedReader.readLine()) != null) 
        {
            result.append(line);
        }
        bufferedReader.close();
        return result.toString();
    }
    
    /**
     * 发送get请求
     *
     * @param url  请求地址
     * @param list 请求参数
     *
     * @return 请求结果
     *
     * @throws IOException
     */
    public static String sendGet(String url, Map<String, String> map)
    		throws IOException {
        StringBuffer buffer = new StringBuffer(); //用来拼接参数
        StringBuffer result = new StringBuffer(); //用来接受返回值
        URL httpUrl = null; //HTTP URL类 用这个类来创建连接
        URLConnection connection = null; //创建的http连接
        BufferedReader bufferedReader = null; //接受连接受的参数
        //如果存在参数,我们才需要拼接参数 类似于 localhost/index.html?a=a&b=b
        
        if (map != null && !map.isEmpty())
        {
        	for (Map.Entry<String, String> entry : map.entrySet())
        	{
        		buffer.append(entry.getKey()).append("=")
        			.append(URLEncoder.encode(entry.getValue(), "utf-8"))
        			.append("&");
        	}
        	//拼完后,去掉最后一个&
        	buffer.deleteCharAt(buffer.length() - 1);
        	url = url + "?" + buffer.toString();
        }
        
        //创建URL
        httpUrl = new URL(url);
        //建立连接
        connection = httpUrl.openConnection();
        connection.setRequestProperty("accept", 
        	"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        connection.setRequestProperty("connection", "keep-alive");
        connection.setRequestProperty("user-agent", 
        	"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0");
        connection.connect();
        //接受连接返回参数
        bufferedReader = new BufferedReader(
        		new InputStreamReader(connection.getInputStream()));
        String line;
        while ((line = bufferedReader.readLine()) != null) 
        {
            result.append(line);
        }
        bufferedReader.close();
        return result.toString();
    }
 
    /**
     * 发送Post请求
     *
     * @param url  请求地址
     * @param list 请求参数
     *
     * @return 请求结果
     *
     * @throws IOException
     */
    public static String sendPost(String url, Map<String, String> map) 
    		throws IOException 
    {
        StringBuffer buffer = new StringBuffer(); //用来拼接参数
        StringBuffer result = new StringBuffer(); //用来接受返回值
        URL httpUrl = null; //HTTP URL类 用这个类来创建连接
        URLConnection connection = null; //创建的http连接
        PrintWriter printWriter = null;
        BufferedReader bufferedReader; //接受连接受的参数
        //创建URL
        httpUrl = new URL(url);
        //建立连接
        connection = httpUrl.openConnection();
        connection.setRequestProperty("accept", 
        	"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        connection.setRequestProperty("connection", "keep-alive");
        connection.setRequestProperty("user-agent", 
        	"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0");
        connection.setDoOutput(true);
        connection.setDoInput(true);
        printWriter = new PrintWriter(connection.getOutputStream());
        if (map != null && !map.isEmpty())
        {
        	for (Map.Entry<String, String> entry : map.entrySet())
        	{
        		buffer.append(entry.getKey()).append("=")
        			.append(URLEncoder.encode(entry.getValue(), "utf-8"))
        			.append("&");
        	}
        	//拼完后,去掉最后一个&
        	buffer.deleteCharAt(buffer.length() - 1);
        	
        }
        
        printWriter.print(buffer.toString());
        printWriter.flush();
        connection.connect();
        //接受连接返回参数
        bufferedReader = new BufferedReader(
        		new InputStreamReader(connection.getInputStream()));
        String line;
        while ((line = bufferedReader.readLine()) != null) 
        {
            result.append(line);
        }
        bufferedReader.close();
        return result.toString();
    }
	
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值