WEB开发网
开发学院软件开发Java URL和HttpCore,HttpClien(不用DNS解析,直接访问... 阅读

URL和HttpCore,HttpClien(不用DNS解析,直接访问使用域名访问的服务器)

 2012-07-06 15:17:14 来源:WEB开发网   
核心提示:package com.feedao.util;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;import java.net.InetAddress;import java.net.I
package com.feedao.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.Socket;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;

import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.DefaultHttpClientConnection;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHttpRequest;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.BasicHttpProcessor;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpProcessor;
import org.apache.http.protocol.HttpRequestExecutor;
import org.apache.http.util.EntityUtils;

public class HttpUtil {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String url = "http://blocker.feedao.com:80/hessian/orderCancel";
		URLTest(url, "102.17.13.49", 80);
		//testHttpClient
		String url2= "http://102.17.13.49:80/hessian/orderCancel";
		testHttpClient(url2, "blocker.feedao.com");
		// 
		try {
			String re = getUrlResult("102.17.13.49", "blocker.feedao.com", "http://blocker.feedao.com:80/hessian/orderCancel");
			System.out.println(re);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	// url http://blocker.feedao.com:80/hessian/orderCancel, ip:102.17.13.49, port:80
	// 使用URL发送请求
	private static void URLTest(String httpUrl, String ip, int port) {
		try {
			URL url = new URL(httpUrl);
			Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(ip, port));
			URLConnection conn = url.openConnection(proxy);
			conn.setDoOutput(true);
			conn.setDoInput(true);
			InputStream in = conn.getInputStream();
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			int bufferSize = 1024 * 1024;
			byte[] buffer = new byte[bufferSize];// 缓冲区
			for (int bytesRead = 0; (bytesRead = in.read(buffer)) != -1;) {
				bos.write(buffer, 0, bytesRead);
				Arrays.fill(buffer, (byte) 0);
			}
			System.out.println(new String(bos.toByteArray(), "UTF-8"));
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	// url http://102.17.13.49:80/hessian/orderCancel, host:blocker.feedao.com
	// 使用HttpClient发送请求
	private static boolean testHttpClient(String url, String host) {
		HttpClient httpclient = new DefaultHttpClient();
		HttpGet httpget = new HttpGet(url);
		if(host !=null && !host.isEmpty()) {
			httpget.addHeader("Host", host);
		}
		httpget.getParams().setParameter(
				CoreConnectionPNames.CONNECTION_TIMEOUT, 5000);
		try {
			HttpResponse response = httpclient.execute(httpget);
			int status = response.getStatusLine().getStatusCode();
			if (status == 500 || status == 200) {
				String context = EntityUtils.toString(response.getEntity());
				if (context.indexOf("only supports POST requests") >= 0) {
					return true;
				}
			}
		} catch (Exception e) {
			// e.printStackTrace();
		}
		return false;
	}
	
	/**
	 * 
	 * @param strIP 可以包含端口号192.168.0.1:8080
	 * @param domain
	 * @param url
	 * @return
	 * @throws Exception
	 */
	public static String getUrlResult(String strIP, String domain, String url) throws Exception {
		String ip = strIP;
		int port = 80;
		if(strIP.contains(":")) {
			String[] ips = strIP.split(":");
			ip = ips[0];
			port = Integer.parseInt(ips[1]);
		}
		if(domain==null || domain.isEmpty()) {
			domain = ip;
		}
		return getUrlResult(ip, domain, url, port);
	}
	
	/**
	 * 请求指定IP的域名下的Url地址
	 * @param strIP 例如:192.168.20.1
	 * @param domain 例如:www.360buy.com
	 * @param url	例如:/index.html
	 * @return 请求连接返回的数据,为空("")表示没有数据
	 * @throws Exception
	 */
	public static String getUrlResult(String strIP, String domain, String url, int port)
			throws Exception {
		
		String result = "";
		// 设置Http协议参数信息
		HttpParams params = new BasicHttpParams();
		HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
		HttpProtocolParams.setContentCharset(params, "UTF-8");
		HttpProtocolParams.setUserAgent(params, "Mozilla/5.0 (Windows NT 6.1)");
		HttpProtocolParams.setHttpElementCharset(params, "UTF-8");
		HttpProtocolParams.setUseExpectContinue(params, false);
		
		HttpProcessor httpproc = new BasicHttpProcessor();
		HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
		HttpContext context = new BasicHttpContext();
		// 创建Http连接对象,需要关闭连接conn.close()
		DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
		try {
			byte[] bytesIP = stringToBytes(strIP);			
			InetAddress inetAddr = InetAddress.getByAddress(domain, bytesIP);
			// 创建socket对象
			Socket socket = new Socket(inetAddr, port);
			conn.bind(socket, params);

			// 创建请求对象
			BasicHttpRequest request = new BasicHttpRequest("GET", url, HttpVersion.HTTP_1_1);
			request.addHeader("Host", domain);
			request.addHeader("Connection", " Keep-Alive");//Close Keep-Alive

			// 执行请求
			httpexecutor.preProcess(request, httpproc, context);
			HttpResponse response = httpexecutor.execute(request, conn, context);
			response.setParams(params);
			httpexecutor.postProcess(response, httpproc, context);
			
			// 获取返回结果
			result = EntityUtils.toString(response.getEntity());
			
			//关闭连接
			conn.close();
		} catch (Exception e) {
//			e.printStackTrace();
			e.toString();
			e.printStackTrace(System.out);
		} finally {
			conn.close();
		}
		return result;
	}
	
	/**
	 * 把字符串的IP转换成byte数组
	 * 
	 * @param ip 例如:192.168.20.1
	 * @return 
	 */
	public static byte[] stringToBytes(String ip) {
		String dotIP = ip.replace('.', ','); // 把IP中的点符号替换成逗号,便于拆分
		String[] nums = dotIP.split(",");
		byte[] bytesIP = { (byte) Integer.parseInt(nums[0]),
				(byte) Integer.parseInt(nums[1]),
				(byte) Integer.parseInt(nums[2]),
				(byte) Integer.parseInt(nums[3]) };
		return bytesIP;
	}

	/**
	 * 把byte数组转换成字符串
	 * 
	 * @param bytes
	 * @return 
	 */
	public static String bytesToString(byte[] bytes) {
		String strIP = (bytes[0] & 0xff) + "." + (bytes[1] & 0xff) + "."
				+ (bytes[2] & 0xff) + "." + (bytes[3] & 0xff);
		return strIP;
	}
}

点击下载此文件

Tags:URL HttpCore HttpClien

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接