HttpURLConnection基本使用【L】

HttpURLConnection可以直接使用,不用下载jar包


代码如下:


package com.lxl.http;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

public class HttpURLTest {

	/**
	 * 发起https请求并获取结果
	 * 
	 * @param requestUrl
	 *            请求地址
	 * @param requestMethod
	 *            请求方式(GET、POST)
	 * @param outputStr
	 *            提交的数据
	 * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
	 */
	public static byte[] httpsRequest(String requestUrl, String requestMethod,
			String outputStr) {
		StringBuffer buffer = new StringBuffer();
		try {
			// 创建SSLContext对象,并使用我们指定的信任管理器初始化
			TrustManager[] tm = { new MyX509TrustManager() };
			SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
			sslContext.init(null, tm, new java.security.SecureRandom());
			// 从上述SSLContext对象中得到SSLSocketFactory对象
			SSLSocketFactory ssf = sslContext.getSocketFactory();

			URL url = new URL(requestUrl);
			HttpsURLConnection httpUrlConn = (HttpsURLConnection) url
					.openConnection();
			httpUrlConn.setSSLSocketFactory(ssf);

			httpUrlConn.setDoOutput(true);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);
			// 设置请求方式(GET/POST)
			httpUrlConn.setRequestMethod(requestMethod);

			// if ("GET".equalsIgnoreCase(requestMethod))
			httpUrlConn.connect();

			// 当有数据需要提交时
			if (null != outputStr) {
				OutputStream outputStream = httpUrlConn.getOutputStream();
				// 注意编码格式,防止中文乱码
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.close();
			}

			// 将返回的输入流转换成字符串
			InputStream inputStream = httpUrlConn.getInputStream();
			return changeInputStream(inputStream);
		} catch (ConnectException ce) {
			ce.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static byte[] requestByPost(String uri, String param) {
		URL url = null;
		try {
			url = new URL(uri);
			HttpURLConnection httpURLConnection = (HttpURLConnection) url
					.openConnection();
			httpURLConnection.setRequestMethod("POST");// 提交模式
			httpURLConnection.setRequestProperty("Content-Type",
					"application/json;charset=utf-8");
			httpURLConnection.setConnectTimeout(10000);// 连接超时 单位毫秒
			httpURLConnection.setReadTimeout(2000);// 读取超时 单位毫秒
			// 发送POST请求必须设置如下两行
			httpURLConnection.setDoOutput(true);
			httpURLConnection.setDoInput(true);
			// 设置cookie
			httpURLConnection.addRequestProperty("Cookie", "myCookies=123");
			// 获取URLConnection对象对应的输出流
			PrintWriter printWriter = new PrintWriter(
					httpURLConnection.getOutputStream());
			// 发送请求参数
			printWriter.write(param);// post的参数 xx=xx&yy=yy
			// flush输出流的缓冲
			printWriter.flush();
			// 获得cookie
			String cookie = httpURLConnection.getHeaderField("set-cookie");
			System.out.println("cookie:::::::::::::" + cookie);
			int repCode = httpURLConnection.getResponseCode();
			System.out.println(repCode);
			// 开始获取数据
			return changeInputStream(httpURLConnection.getInputStream());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static byte[] requestByGetSync(String uri) {
		URL url = null;
		try {
			url = new URL(uri);
			HttpURLConnection httpURLConnection = (HttpURLConnection) url
					.openConnection();
			httpURLConnection.setRequestMethod("GET");// 提交模式
			httpURLConnection.setConnectTimeout(10000);// 连接超时 单位毫秒
			httpURLConnection.setReadTimeout(2000);// 读取超时 单位毫秒
			httpURLConnection.connect();
			int repCode = httpURLConnection.getResponseCode();
			System.out.println(repCode);
			// 开始获取数据
			return changeInputStream(httpURLConnection.getInputStream());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static byte[] changeInputStream(InputStream inputStream) {
		// TODO Auto-generated method stub
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		int len = 0;
		byte[] date = new byte[1024];
		try {
			while ((len = inputStream.read(date)) != -1) {
				outputStream.write(date, 0, len);
			}
			return outputStream.toByteArray();
			// result = new String(outputStream.toByteArray(), encode);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				outputStream.close();
				inputStream.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return null;
	}

	public static void main(String[] args) throws Exception {
		String UUID = "";
		String uri = "https://login.weixin.qq.com/jslogin?appid=wx782c26e4c19acffb"
				+ "&redirect_uri=https%3A%2F%2Fwx.qq.com%2Fcgi-bin%2Fmmwebwx-bin%2Fwebwxnewloginpage&fun=new&"
				+ "lang=zh_CN&_=" + System.currentTimeMillis();
		// 防止报如下错
		// javax.net.ssl.SSLProtocolException: handshake alert:
		// unrecognized_name
		System.setProperty("jsse.enableSNIExtension", "false");
		// String returnStr = new String(requestByGetSync(uri), "UTF-8");
		String returnStr = new String(httpsRequest(uri, "GET", null), "UTF-8");
		if (null != returnStr && !"".equals(returnStr)) {
			System.out.println(returnStr);
			if (returnStr.indexOf("200") != -1) {
				UUID = returnStr.substring(returnStr.length() - 14,
						returnStr.length() - 2);
			}
		}
		System.out.println(UUID);
	}
}


你可能感兴趣的:(java技术,HTTPCLIENT,爬虫)