Java HttpURLConnection类使用示例

package com.vps.api.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.zip.GZIPInputStream;
import java.util.zip.InflaterInputStream;

import javax.net.ssl.HttpsURLConnection;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

public class HttpURLConnectionTest {

	public final static Logger log = Logger.getLogger(AccessUmUtil.class);

	/**
	 * 将input流转成String
	 * 
	 * @param paramInputStream
	 * @return
	 */
	private static String inputStreamToString(InputStream paramInputStream) {
		BufferedReader localBufferedReader = new BufferedReader(
				new InputStreamReader(paramInputStream), 8192);
		StringBuilder localStringBuilder = new StringBuilder();

		Object localObject1 = null;
		try {
			while ((localObject1 = localBufferedReader.readLine()) != null)
				localStringBuilder.append(localObject1 + "\n");
		} catch (IOException localIOException1) {
			return null;
		} finally {
			try {
				paramInputStream.close();
			} catch (IOException localIOException3) {
				return null;
			}
		}
		return localStringBuilder.toString();
	}
	
	private static int visitUrl(String url, Map<String, String> httpHeaderMap, String keyword) {
		long start = System.currentTimeMillis();
		try {
			URL urlLink = new URL(url);
			/**
			 * HttpURLConnection并不是底层的连接,而是在底层连接上的一个请求,是一个抽象类,自身不能被实例化。只能通过URL.
			 * openConnection()方法创建具体的实例。
			 */
			URLConnection urlConnection = urlLink.openConnection();
			HttpURLConnection connection = (HttpURLConnection) urlConnection;
			if (url.toLowerCase().trim().startsWith("https")) {
				connection = (HttpsURLConnection) urlConnection;
			}
			connection.setConnectTimeout(10000); // 设置连接超时时间
			connection.setReadTimeout(10000); // 设置读取超时时间
			
			/** 允许Input、Output、不使用Cache、不重定向 */  
			connection.setDoInput(true);  
			connection.setDoOutput(true);  
			connection.setUseCaches(false);
			connection.setInstanceFollowRedirects(false);
			
			/** 设置header参数 */
			if ((httpHeaderMap != null) && (httpHeaderMap.size() > 0)) {
				Set<String> set = httpHeaderMap.keySet();
				for (String key : set) {
					connection.setRequestProperty(key.trim(), httpHeaderMap.get(key).trim());
				}
			}
			connection.connect(); // 发送链接
			log.info("url:" + url + "\n--返回状态:" + connection.getResponseCode());
			/** 发送不成功 */
			if (HttpURLConnection.HTTP_OK != connection.getResponseCode()) {
				// 重定向
				if (HttpURLConnection.HTTP_MOVED_PERM == connection.getResponseCode()
						|| HttpURLConnection.HTTP_MOVED_TEMP == connection.getResponseCode()) {
					visitUrl(connection.getHeaderField("Location"), httpHeaderMap, keyword);
				}
				return -1;
			}
			
			/** 发送成功,处理数据, 取得响应内容 */
			InputStream inputStream = connection.getInputStream();
			if (inputStream != null) {
				String encode = connection.getContentEncoding();
				if ("gzip".equalsIgnoreCase(encode)) {
					inputStream = new GZIPInputStream(inputStream);
				} else if ("deflategzip".equalsIgnoreCase(encode)) {
					inputStream = new InflaterInputStream(inputStream);
				}

				String body = inputStreamToString(inputStream);
				if (StringUtils.isNotBlank(keyword)) {
					if (StringUtils.isBlank(body) || body.indexOf(keyword) < 0) {
						log.error("未返回正确内容:" + body);
						return -1;
					}
				}
			}
			inputStream.close();// 关闭InputStream
			
			int spent = (int) (System.currentTimeMillis() - start);
			return spent;
		} catch (MalformedURLException e) {
			log.error(" not valid, " + e.getMessage(), e);
		} catch (IOException e) {
			log.error(" not valid, " + e.getMessage(), e);
		}
		return -1;
	}
	
	public static void main(String[] args) {
		Map<String, String> httpHeaderMap = new HashMap<String, String>();
		httpHeaderMap.put("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 9_2 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13C75 Safari/601.1");
		String url = "http://botuu.adsame.com/c?z=botuu&la=0&si=160&c=1142&cg=633&ci=122&or=150&l=1478&bg=1478&b=1478&u=https://abc.tmall.com";
		visitUrl(url, httpHeaderMap, "abc");
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值