HttpClient入门

1.HttpClient简介

HTTP协议可能是现在 Internet 上使用得最多、最重要的协议了,越来越多的 Java 应用程序需要直接通过 HTTP 协议来访问网络资源。虽然在 JDK 的 java.net 包中已经提供了访问 HTTP 协议的基本功能,但是对于大部分应用程序来说,JDK 库本身提供的功能还不够丰富和灵活。HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。HttpClient 已经应用在很多的项目中,比如 Apache Jakarta 上很著名的另外两个开源项目 Cactus 和 HTMLUnit 都使用了 HttpClient,更多使用 HttpClient 的应用可以参见

2.HttpClient功能介绍

以下列出的是 HttpClient 提供的主要的功能,要知道更多详细的功能可以参见HttpClient 的主页。

  • 实现了所有 HTTP 的方法(GET,POST,PUT,HEAD 等)
  • 支持自动转向
  • 支持 HTTPS 协议
  • 支持代理服务器等

下面将逐一介绍怎样使用这些功能。首先,我们必须安装好 HttpClient。

HttpClient基本功能的使用

Get方法

使用 HttpClient 需要以下 6 个步骤:

1. 创建 HttpClient 的实例

2. 创建某种连接方法的实例,在这里是 GetMethod。在 GetMethod 的构造函数中传入待连接的地址

3. 调用第一步中创建好的实例的 execute 方法来执行第二步中创建好的 method 实例

4. 读 response

5. 释放连接。无论执行方法是否成功,都必须释放连接

6. 对得到后的内容进行处理

 根据以上步骤,我们来编写用GET方法来取得某网页内容的代码。

 1.大部分情况下 HttpClient 默认的构造函数

  HttpClient httpClient = new HttpClient();

  2.创建GET方法的实例,

       在GET方法的构造函数中传入待连接的地址即可,用GetMethod将会自动处理转发过程,如果想要把自动处理转发过程去掉的话,可以调用方法setFollowRedirects(false)。
GetMethod getMethod = new GetMethod("http://www.hust.edu.com");

3.调用实例httpClient的executeMethod方法来执行getMethod。由于是执行在网络上的程序,在运行executeMethod方法的时候,需要处理两个异常,分别是HttpException和IO     Exception。引起第一种异常的原因主要可能是在构造getMethod的时候传入的协议不对,比如不小心将"http"写成"htp",或者服务器端返回的内容不正常等,并且该异常发生      是不可恢复的;第二种异常一般是由于网络原因引起的异常,对于这种异常(IOException),HttpClient会根据你指定的恢复策略自动试着重新执行executeMethod方法。Http Client的恢复策略可以自定义(通过实现接口HttpMethodRetryHandler的类来实现)。通过httpClient的方法setParameter设置你实现的恢复策略,本文中使用的是系统提供的默认恢复策略,该策略在碰到第二类异常的时候将自动重试3次。executeMethod返回值是一个整数,表示了执行该方法后服务器返回的状态码,该状态码能表示出该方法执行是否成功、需要认证或者页面发生了跳转(默认状态下GetMethod的实例是自动处理跳转的)等.

   

//设置成了默认的恢复策略,在发生异常时候将自动重试3次,在这里你也可以设置成自定义的恢复策略
getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); 
//执行getMethod
int statusCode = client.executeMethod(getMethod);
if (statusCode != HttpStatus.SC_OK) {
  System.err.println("Method failed: " + getMethod.getStatusLine());
}
4.在返回的状态码正确后,即可取得内容

  取得目标地址的内容有三种方法:第一种,getResponseBody,该方法返回的是目标的二进制的byte流;第二种,getResponseBodyAsString,这个方法返回的是String类       型,值得注意的是该方法返回的String的编码是根据系统默认的编码方式,所以返回的String值可能编码类型有误,在本文的"字符编码"部分中将对此做详细介绍;第三种,  getResponseBodyAsStream,这个方法对于目标地址中有大量数据需要传输是最佳的。在这里我们使用了最简单的getResponseBody方法。

    byte[] responseBody = method.getResponseBody();
5.释放连接

   注意:无论执行方法是否成功,都必须释放连接

   method.releaseConnection();
6.处理内容,在这一步中根据你的需要处理内容。

  System.out.println(new String(responseBody));

  下面是一段完整的程序:

   

<pre name="code" class="java">package com.tds.commons;

import java.io.IOException;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

/**
 * http get方式
 * @author Administrator
 *
 */
public class HttpGetTest {

	public static void main(String[] args) {
		// 构造HttpClient的实例
		HttpClient httpClient = new HttpClient();  //3.1版本
		// 创建GET方法的实例
		GetMethod getMethod = new GetMethod("http://www.hust.edu.com");
		// 使用系统提供的默认的恢复策略
		getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
		try {
			// 执行getMethod
			int statusCode = httpClient.executeMethod(getMethod);
			if (statusCode != HttpStatus.SC_OK) {
				System.err.println("Method failed: " + getMethod.getStatusLine());
			}
			// 读取内容
			byte[] responseBody = getMethod.getResponseBody();
			// 处理内容
			System.out.println(new String(responseBody));
		} catch (HttpException e) {
			// 发生致命的异常,可能是协议不对或者返回的内容有问题
			System.out.println("Please check your provided http address!");
			e.printStackTrace();
		} catch (IOException e) {
			// 发生网络异常
			e.printStackTrace();
		} finally {
			// 释放连接
			getMethod.releaseConnection();
		}
	}
}

 打印的结果如下: 
<!DOCTYPE html ><html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" dir="ltr"
  xmlns:content="http://purl.org/rss/1.0/modules/content/"
  xmlns:dc="http://purl.org/dc/terms/"
  xmlns:foaf="http://xmlns.com/foaf/0.1/"
  xmlns:og="http://ogp.me/ns#"
  xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#"
  xmlns:sioc="http://rdfs.org/sioc/ns#"
  xmlns:sioct="http://rdfs.org/sioc/types#"
  xmlns:skos="http://www.w3.org/2004/02/skos/core#"
  xmlns:xsd="http://www.w3.org/2001/XMLSchema#">
<head profile="http://www.w3.org/1999/xhtml/vocab">
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="Drupal 7 (http://drupal.org)" />
<link rel="canonical" href="http://www.hust.edu.com/home" />
<link rel="shortlink" href="http://www.hust.edu.com/home" />
<meta name="description" content="edu.com is our one-stop guide to universities, colleges, online courses and online degrees. Get started today!" />
<meta content="edu.com-home" about="/home" property="dc:title" />
<meta http-equiv="x-dns-prefetch-control" content="on" />
<link rel="dns-prefetch" href="//images.vantage-media.net" />
<link rel="shortcut icon" href="//images.vantage-media.net/d/sites/default/files/assets/verticals/education/edu.com/desktop/default/images/favicon.ico" type="image/vnd.microsoft.icon" data-inserted-by="favicon_by_path" />
  <title>edu.com | Browse Top Colleges & Universities</title>
  

<link href="//fonts.googleapis.com/css?family=Montserrat:400,700'" rel="stylesheet" type="text/css">  

  <style type="text/css" media="all">@import url("//images.vantage-media.net/d/modules/system/system.base.css?n9jkwa");
@import url("//images.vantage-media.net/d/modules/system/system.menus.css?n9jkwa");
@import url("//images.vantage-media.net/d/modules/system/system.messages.css?n9jkwa");
@import url("//images.vantage-media.net/d/modules/system/system.theme.css?n9jkwa");</style>
<style type="text/css" media="all">@import url("//images.vantage-media.net/d/sites/all/modules/date/date_api/date.css?n9jkwa");
@import url("//images.vantage-media.net/d/modules/field/theme/field.css?n9jkwa");
@import url("//images.vantage-media.net/d/modules/node/node.css?n9jkwa");
@import url("//images.vantage-media.net/d/modules/search/search.css?n9jkwa");
@import url("//images.vantage-media.net/d/modules/user/user.css?n9jkwa");
@import url("//images.vantage-media.net/d/profiles/plato_tipico/modules/views/css/views.css?n9jkwa");</style>
<style type="text/css" media="all">@import url("//images.vantage-media.net/d/profiles/plato_tipico/modules/ctools/css/ctools.css?n9jkwa");
@import url("//images.vantage-media.net/d/sites/all/modules/lightbox2/css/lightbox_alt.css?n9jkwa");
@import url("//images.vantage-media.net/d/sites/all/modules/nice_menus/nice_menus.css?n9jkwa");
@import url("//images.vantage-media.net/d/sites/all/modules/nice_menus/nice_menus_default.css?n9jkwa");
@import url("//images.vantage-media.net/d/sites/all/modules/panels/css/panels.css?n9jkwa");
@import url("//images.vantage-media.net/d/themes/seven/layouts/fivecols_topFocus_columns_wrapped/fivecols_topFocus_columns_wrapped.css?n9jkwa");</style>
<link type="text/css" rel="stylesheet" href="//images.vantage-media.net/d/sites/default/files/assets/verticals/education/edu.com/desktop/default/css/common.min.css?n9jkwa" media="all" />
<link type="text/css" rel="stylesheet" href="//images.vantage-media.net/d/sites/default/files/assets/verticals/education/edu.com/desktop/default/css/results.min.css?n9jkwa" media="all" />
<style type="text/css" media="screen">@import url("//images.vantage-media.net/d/themes/seven/reset.css?n9jkwa");
@import url("//images.vantage-media.net/d/themes/seven/style.css?n9jkwa");</style>

<!--[if lte IE 8]>
<link type="text/css" rel="stylesheet" href="//images.vantage-media.net/d/themes/seven/ie.css?n9jkwa" media="all" />
<![endif]-->

<!--[if lte IE 7]>
<link type="text/css" rel="stylesheet" href="//images.vantage-media.net/d/themes/seven/ie7.css?n9jkwa" media="all" />
<![endif]-->

<!--[if lte IE 6]>
<link type="text/css" rel="stylesheet" href="//images.vantage-media.net/d/themes/seven/ie6.css?n9jkwa" media="all" />
<![endif]-->
  <script type="text/javascript" src="//images.vantage-media.net/d/sites/all/modules/custom/jquery_update/replace/jquery/1.7/jquery.js?v=1.7.1"></script>
<script type="text/javascript" src="//images.vantage-media.net/d/misc/jquery.once.js?v=1.2"></script>
<script type="text/javascript" src="//images.vantage-media.net/d/misc/drupal.js?n9jkwa"></script>
<script type="text/javascript">
<!--//--><![CDATA[//><!--
jQuery.extend(Drupal.settings, {"basePath":"\/","pathPrefix":"","ajaxPageState":{"theme":"seven","theme_token":"D3ADSujxTklKnBu9vcmh0jXHsqz-o_58gKsl3VJkq50","js":{"sites\/all\/modules\/custom\/jquery_update\/replace\/jquery\/1.7\/jquery.js":1,"misc\/jquery.once.js":1,"misc\/drupal.js":1,"sites\/all\/modules\/admin_menu\/admin_devel\/admin_devel.js":1,"\/\/images.vantage-media.net\/d\/\/sites\/default\/files\/assets\/commons\/jquery.cookie.min.js":1,"\/\/images.vantage-media.net\/d\/\/sites\/default\/files\/assets\/commons\/jquery.validate.min.js":1,"\/\/images.vantage-media.net\/d\/\/sites\/default\/files\/assets\/commons\/additional-methods.min.js":1,"\/\/images.vantage-media.net\/d\/\/sites\/default\/files\/assets\/testntarget\/mbox.js":1,"\/\/images.vantage-media.net\/d\/\/sites\/default\/files\/assets\/sitecatalyst\/event-tracking.min.js":1,"\/\/images.vantage-media.net\/d\/\/sites\/default\/files\/assets\/sitecatalyst\/results-tracking.min.js":1,"\/\/images.vantage-media.net\/d\/\/sites\/default\/files\/assets\/commons\/common-functions.min.js":1,"\/\/images.vantage-media.net\/d\/\/sites\/default\/files\/assets\/commons\/form-validations.min.js":1,"sites\/all\/modules\/lightbox2\/js\/lightbox.js":1,"sites\/all\/modules\/nice_menus\/superfish\/js\/superfish.js":1,"sites\/all\/modules\/nice_menus\/superfish\/js\/hoverIntent.js":1,"sites\/all\/modules\/nice_menus\/nice_menus.js":1,"sites\/all\/modules\/panels\/js\/panels.js":1,"sites\/default\/files\/assets\/verticals\/education\/edu.com\/desktop\/default\/js\/common.min.js":1,"sites\/default\/files\/assets\/verticals\/education\/edu.com\/desktop\/default\/js\/results.min.js":1,"sites\/default\/files\/assets\/verticals\/education\/edu.com\/desktop\/default\/js\/tnt-results.min.js":1,"sites\/default\/files\/assets\/listings\/vm-load-edu.min.js":1,"sites\/default\/files\/assets\/commons\/mapsvg.min.js":1,"sites\/default\/files\/assets\/commons\/raphael.min.js":1,"sites\/default\/files\/assets\/commons\/html5shiv.min.js":1,"sites\/default\/files\/assets\/verticals\/education\/edu.com\/desktop\/default\/js\/custom-edu.min.js":1,"0":1,"themes\/seven\/jquery.mb.browser.min.js":1},"css":{"modules\/system\/system.base.css":1,"modules\/system\/system.menus.css":1,"modules\/system\/system.messages.css":1,"modules\/system\/system.theme.css":1,"sites\/all\/modules\/date\/date_api\/date.css":1,"modules\/field\/theme\/field.css":1,"modules\/node\/node.css":1,"modules\/search\/search.css":1,"modules\/user\/user.css":1,"profiles\/plato_tipico\/modules\/views\/css\/views.css":1,"profiles\/plato_tipico\/modules\/ctools\/css\/ctools.css":1,"sites\/all\/modules\/lightbox2\/css\/lightbox_alt.css":1,"sites\/all\/modules\/nice_menus\/nice_menus.css":1,"sites\/all\/modules\/nice_menus\/nice_menus_default.css":1,"sites\/all\/modules\/panels\/css\/panels.css":1,"themes\/seven\/layouts\/fivecols_topFocus_columns_wrapped\/fivecols_topFocus_columns_wrapped.css":1,"sites\/default\/files\/assets\/verticals\/education\/edu.com\/desktop\/default\/css\/common.min.css":1,"sites\/default\/files\/assets\/verticals\/education\/edu.com\/desktop\/default\/css\/results.min.css":1,"themes\/seven\/reset.css":1,"themes\/seven\/style.css":1,"themes\/seven\/ie.css":1,"themes\/seven\/ie7.css":1,"themes\/seven\/ie6.css":1}},"lightbox2":{"rtl":"0","file_path":"\/(\\w\\w\/)public:\/","default_image":"\/sites\/all\/modules\/lightbox2\/images\/brokenimage.jpg","border_size":10,"font_color":"000","box_color":"fff","top_position":"","overlay_opacity":"0.8","overlay_color":"000","disable_close_click":1,"resize_sequence":0,"resize_speed":400,"fade_in_speed":400,"slide_down_speed":600,"use_alt_layout":1,"disable_resize":0,"disable_zoom":0,"force_show_nav":1,"show_caption":1,"loop_items":0,"node_link_text":"View Image Details","node_link_target":"_blank","image_count":"Image !current of !total","video_count":"Video !current of !total","page_count":"Page !current of !total","lite_press_x_close":"press \u003Ca href=\u0022#\u0022 οnclick=\u0022hideLightbox(); return FALSE;\u0022\u003E\u003Ckbd\u003Ex\u003C\/kbd\u003E\u003C\/a\u003E to close","download_link_text":"","enable_login":false,"enable_contact":false,"keys_close":"c x 27","keys_previous":"p 37","keys_next":"n 39","keys_zoom":"z","keys_play_pause":"32","display_image_size":"original","image_node_sizes":"()","trigger_lightbox_classes":"","trigger_lightbox_group_classes":"","trigger_slideshow_classes":"","trigger_lightframe_classes":"","trigger_lightframe_group_classes":"","custom_class_handler":0,"custom_trigger_classes":"","disable_for_gallery_lists":true,"disable_for_acidfree_gallery_lists":true,"enable_acidfree_videos":true,"slideshow_interval":5000,"slideshow_automatic_start":true,"slideshow_automatic_exit":true,"show_play_pause":true,"pause_on_next_click":false,"pause_on_previous_click":true,"loop_slides":false,"iframe_width":600,"iframe_height":400,"iframe_border":1,"enable_video":0},"nice_menus_options":{"delay":800,"speed":1},"Vantage":{"marketplace_configs":{"debug":false,"ENVIRONMENT":"prod","ASSETS_VERSION":"min","MARKETPLACES_URL":"\/\/marketplaces.vantagemedia.com\/search\/?format=json","PARTICIPANTS_URL":"\/\/marketplaces.vantagemedia.com\/searchparticipants\/?format=json","LEAD_POSTING_URL":"\/\/marketplaces.vantagemedia.com\/lead?format=json","VM_APP_URL":"sites\/default\/files\/assets\/listings\/vm_app.js","VM_APP_BASE_URL":"sites\/default\/files\/assets\/listings\/vm_app.js","VM_APP_EDU_FUNCTIONS":"sites\/default\/files\/assets\/listings\/vm_app_edu.js","JQUERY_URL":"sites\/default\/files\/assets\/commons\/jquery.js?v=1.7.1","JSON_URL":"sites\/default\/files\/assets\/commons\/json2.js","GEO_IP_URL":"\/\/geo.vantagemedia.com\/vm_geo.php","CITY_STATE_URL":"\/\/piv.vantagemedia.com\/getCityAndState.php?format=json","HEADER_URL":"\/\/publishers.vantagemedia.com\/header.php","DRUPAL_ASSETS_PATH_BASE":"\/\/images.vantage-media.net\/d\/","IMPLEMENTATIONS_PATH_BASE":"\/\/images.vantage-media.net\/p\/","IMPLEMENTATIONS_ASSETS_PATH_BASE":"\/\/images.vantage-media.net\/p\/ly\/"},"parameters":[],"tracking_parameters":{"node_id":"536","funnel_taxonomy_id":"185","funnel_vocabulary_id":"8","funnel_taxonomy_name":"edu.com","funnel_start":"1","sc_report_suite_id":"vantageeducom","funnel_id":"6"}}});
//--><!]]>
</script>
<script type="text/javascript" src="//images.vantage-media.net/d/sites/all/modules/admin_menu/admin_devel/admin_devel.js?n9jkwa"></script>
<script type="text/javascript" src="//images.vantage-media.net/d//sites/default/files/assets/commons/jquery.cookie.min.js?n9jkwa"></script>
<script type="text/javascript" src="//images.vantage-media.net/d//sites/default/files/assets/commons/jquery.validate.min.js?n9jkwa"></script>
<script type="text/javascript" src="//images.vantage-media.net/d//sites/default/files/assets/commons/additional-methods.min.js?n9jkwa"></script>
<script type="text/javascript" src="//images.vantage-media.net/d//sites/default/files/assets/testntarget/mbox.js?n9jkwa"></script>
<script type="text/javascript" src="//images.vantage-media.net/d//sites/default/files/assets/sitecatalyst/event-tracking.min.js?n9jkwa"></script>
<script type="text/javascript" src="//images.vantage-media.net/d//sites/default/files/assets/sitecatalyst/results-tracking.min.js?n9jkwa"></script>
<script type="text/javascript" src="//images.vantage-media.net/d//sites/default/files/assets/commons/common-functions.min.js?n9jkwa"></script>
<script type="text/javascript" src="//images.vantage-media.net/d//sites/default/files/assets/commons/form-validations.min.js?n9jkwa"></script>
<script type="text/javascript" src="//images.vantage-media.net/d/sites/all/modules/lightbox2/js/lightbox.js?1410487040"></script>
<script type="text/javascript" src="//images.vantage-media.net/d/sites/all/modules/nice_menus/superfish/js/superfish.js?n9jkwa"></script>
<script type="text/javascript" src="//images.vantage-media.net/d/sites/all/modules/nice_menus/superfish/js/hoverIntent.js?n9jkwa"></script>
<script type="text/javascript" src="//images.vantage-media.net/d/sites/all/modules/nice_menus/nice_menus.js?n9jkwa"></script>
<script type="text/javascript" src="//images.vantage-media.net/d/sites/all/modules/panels/js/panels.js?n9jkwa"></script>
<script type="text/javascript" src="//images.vantage-media.net/d/sites/default/files/assets/verticals/education/edu.com/desktop/default/js/common.min.js?n9jkwa"></script>
<script type="text/javascript" src="//images.vantage-media.net/d/sites/default/files/assets/verticals/education/edu.com/desktop/default/js/results.min.js?n9jkwa"></script>
<script type="text/javascript" src="//images.vantage-media.net/d/sites/default/files/assets/verticals/education/edu.com/desktop/default/js/tnt-results.min.js?n9jkwa"></script>
<script type="text/javascript" src="//images.vantage-media.net/d/sites/default/files/assets/listings/vm-load-edu.min.js?n9jkwa"></script>
<script type="text/javascript" src="//images.vantage-media.net/d/sites/default/files/assets/commons/mapsvg.min.js?n9jkwa"></script>
<script type="text/javascript" src="//images.vantage-media.net/d/sites/default/files/assets/commons/raphael.min.js?n9jkwa"></script>
<script type="text/javascript" src="//images.vantage-media.net/d/sites/default/files/assets/commons/html5shiv.min.js?n9jkwa"></script>
<script type="text/javascript" src="//images.vantage-media.net/d/sites/default/files/assets/verticals/education/edu.com/desktop/default/js/custom-edu.min.js?n9jkwa"></script>
<script type="text/javascript">
<!--//--><![CDATA[//><!--
var kid =""; 
function scTracking(data) { 
var interactionId = ""; 
var userId = ""; 
if (data != null) { 
if(data.UserId !== undefined && data.UserId.length > 0){ 
saveCookie(data.UserIdCookieName, data.UserId, 30); 
var fieldUserIdVal = jQuery("[name=userId]").val(data.UserId); 
userId = data.UserId; 
} 
if(data.InteractionId !== undefined && data.InteractionId.length > 0){ 
saveCookie(data.InteractionIdCookieName, data.InteractionId, 30); 
var fieldIntVal = jQuery("[name=field_interaction_id]").val(data.InteractionId); 
var fieldIntIdVal = jQuery("[name=interactionId]").val(data.InteractionId); 
interactionId = data.InteractionId; 
} 
} 
if(interactionId === undefined || interactionId == "" || interactionId.lenght == 0){ 
interactionId = jQuery("[name=interactionId]").val(); 
} 
if(interactionId === undefined || interactionId == "" || interactionId.lenght == 0){ 
interactionId = jQuery("[name=field_interaction_id]").val(); 
} 
if(interactionId === undefined || interactionId == "" || interactionId.lenght == 0){ 
interactionId = getCookie("_VMI"); 
var fieldIntVal = jQuery("[name=field_interaction_id]").val(interactionId); 
var fieldIntIdVal = jQuery("[name=interactionId]").val(interactionId); 
} 
if(userId === undefined || userId == "" || userId.lenght == 0){ 
userId = jQuery("[name=userId]").val(); 
} 
if(userId === undefined || userId == "" || userId.lenght == 0){ 
userId = getCookie("_VMU"); 
var fieldUserIdVal = jQuery("[name=userId]").val(userId); 
} 
s.prop1 = window.adSource;  // KID
s.prop2 = userId; //User Id
s.prop3 = interactionId; //Interaction Id
s.prop4 = Drupal.settings.Vantage.tracking_parameters.session_id; // Php Session ID
s.prop5 = Drupal.settings.Vantage.tracking_parameters.funnel_start;
s.prop6 = Drupal.settings.Vantage.tracking_parameters.funnel_id;
s.prop7 = Drupal.settings.Vantage.tracking_parameters.funnel_taxonomy_name;
s.prop8 = Drupal.settings.Vantage.parameters.cid;

s.eVar23 = s.prop2;
s.eVar24 = s.prop3;

s.pageType="Partnership Page";

s.eVar22 = window.adSource;
if(typeof s.campaign=== 'undefined' || !s.campaign|| s.campaign.length == 0){
    s.campaign = window.adSource;
}

window.referralSite = getReferralSite();
if(window.referralSite!== undefined && window.referralSite!= null){
s.eVar30 = window.referralSite;
}

window.referralDomain= getReferralDomain();
if(window.referralDomain!== undefined && window.referralDomain!= null){
s.eVar31 = window.referralDomain;
}

if(typeof s.pageName === 'undefined' || !s.pageName || s.pageName.length == 0){
    s.pageName= "";
}

vm_sitecatalyst.setCustomEvents(s); 
 
if (typeof s.t !== 'undefined') { 
var s_code=s.t(); 
if (s_code) 
{ 
document.write(s_code); 
} 
} 
} 

//--><!]]>
</script>
<script type="text/javascript" src="//images.vantage-media.net/d/themes/seven/jquery.mb.browser.min.js?n9jkwa"></script>
  

</head>
<body class="html not-front not-logged-in no-sidebars page-node page-node- page-node-536 node-type-panel domain-edu-com i18n-en" >

  <div id="skip-link">
    <a href="#main-content" class="element-invisible element-focusable">Skip to main content</a>
  </div -->

    
  <div id="branding" class="clearfix">
    <h2 class="element-invisible">You are here</h2><div class="breadcrumb"><a href="/">Home</a></div>              <h1 class="page-title">edu.com-home</h1>
              </div>


  <div id="page">
  
        <div class="region region-content">
    <div id="block-system-main" class="block block-system">

    
  <div class="content">
    <div id="node-536" class="node node-panel node-promoted clearfix" about="/home" typeof="sioc:Item foaf:Document">

  
      
  
  <div class="content">
    <span class="print-link"></span>
    <div class="page-wrap clear-block">
        <div class="portal-wrap clear-block">
            <div class="header-wrap clear-block"><header id="header"><section class="container"><div id="header-top"><div class="logo"></div><h1>Browse Top Colleges & Universities</h1></div><div id="header-bottom"><form action="/results" method="post" id="redefine-edu" accept-charset="UTF-8" novalidate="novalidate"><div><div class="pre-intructions"></div><input id="field_interaction_id" name="interactionId" type="hidden" /> <input id="field_ad_source" name="adSource" type="hidden" /> <input id="field-kid" name="kid" type="hidden" /> <input id="field-user-id" name="userId" type="hidden" /> <input id="field-src-kid-id" name="srcKid" type="hidden" /> <input id="field-type-kid-id" name="typeKid" type="hidden" /> <input id="field-referral-site" name="referralSite" type="hidden" /><input id="field-referral-domain" type="hidden" name="referralDomain" /><div id="field-area-of-study-wrapper" class="item-wrapper"><div class="form-type-select"><label for="field-area-of-study">Area of Study </label><select id="field-area-of-study" name="areaOfStudy" class="form-select"><option value="" selected="selected">-- Select Area of Study --</option><option value="1">Business</option><option value="2">Creative Arts & Design</option><option value="3">Criminal Justice & Security</option><option value="4">Culinary</option><option value="5">Education</option><option value="6">Engineering</option><option value="7">General</option><option value="8">Health Care & Human Services</option><option value="9">IT & Computer Science</option><option value="10">Legal</option><option value="11">Medical</option><option value="12">Nursing</option><option value="13">Psychology & Social Services</option><option value="14">Trade & Vocational</option></select></div></div><div id="field-sub-area-of-study-wrapper" class="item-wrapper"><div class="form-type-select"><label for="field-sub-area-of-study">Concentration </label><select id="field-sub-area-of-study" name="subAreaOfStudy" class="form-select"><option value="" selected="selected">-- Select Concentration --</option></select></div></div><div id="field-zip-code-wrapper" class="item-wrapper"><div class="form-type-textfield"><label for="field-zip-code">Zip Code </label> <input class="form-text" id="field-zip-code" name="location" value="" size="60" maxlength="5" type="text" /></div></div><input id="submitButton" name="submit" value="search ►" class="form-submit yellow-button" type="submit" /></div></form></div></section></header></div>
            <div class="column1 clear-block"><div id="pocket-results-title-arrow"></div></div>
			<div class="columns-wrapper">
				<div class="column2 clear-block">					<div class="pocket-assembly">											
						<div id="pocket-results-title">
							<p class="pocket-results" style="display: block;">Below are Your <span class="pocket-program" data-mce-mark="1">General</span> Schools in <span class="pocket-state" data-mce-mark="1">California</span></p>
							<h1 class="pocket-title">Select from these Top Colleges & Universities</h1>
						</div>
					</div><section id="vm-results"></section><div id="advertiser-link"><a id="advertiser-network-link" href="http://www.vantagemedia.com/advertisers/" target="_blank">Join our provider network</a></div></div>
				<div class="column3 clear-block"><p>Edu.com is your one-stop guide to universities, colleges, online curses and online degress. Whether you're just starting out and or you know exactly which degree program you want to enroll in, Edu.com can help. Get started with your online education today!</p>
<h2>BROWSE COLLEGES BY STATE</h2>
<p>Select a state from below</p>
<div id="mapsvg"></div>
<ul class="states">
   <li id="state-alaska" name="AK">Alaska</li>
   <li id="state-alabama" name="AL">Alabama</li>
   <li id="state-arkansas" name="AR">Arkansas</li>
   <li id="state-arizona" name="AZ">Arizona</li>
   <li id="state-california" name="CA">California</li>
   <li id="state-colorado" name="CO">Colorado</li>
   <li id="state-connecticut" name="CT">Connecticut</li>
   <li id="state-delaware" name="DE">Delaware</li>
   <li id="state-florida" name="FL">Florida</li>
   <li id="state-georgia" name="GA">Georgia</li>
   <li id="state-hawaii" name="HI">Hawaii</li>
   <li id="state-iowa" name="IA">Iowa</li>
   <li id="state-idaho" name="ID">Idaho</li>
   <li id="state-illinois" name="IL">Illinois</li>
   <li id="state-indiana" name="IN">Indiana</li>
   <li id="state-kansas" name="KS">Kansas</li>
   <li id="state-kentucky" name="KY">Kentucky</li>
</ul>
<ul class="states">
   <li id="state-louisiana" name="LA">Louisiana</li>
   <li id="state-maine" name="ME">Maine</li>
   <li id="state-massachusetts" name="MA">Massachusetts</li>
   <li id="state-maryland" name="MD">Maryland</li>
   <li id="state-michigan" name="MI">Michigan</li>
   <li id="state-minnesota" name="MN">Minnesota</li>
   <li id="state-missouri" name="MO">Missouri</li>
   <li id="state-mississippi" name="MS">Mississippi</li>
   <li id="state-montana" name="MT">Montana</li>
   <li id="state-north carolina" name="NC">North Carolina</li>
   <li id="state-north dakota" name="ND">North Dakota</li>
   <li id="state-nebraska" name="NE">Nebraska</li>
   <li id="state-new hampshire" name="NH">New Hampshire</li>
   <li id="state-new jersey" name="NJ">New Jersey</li>
   <li id="state-new mexico" name="NM">New Mexico</li>
   <li id="state-nevada" name="NV">Nevada</li>
   <li id="state-new york" name="NY">New York</li>
</ul>
<ul class="states">
   <li id="state-ohio" name="OH">Ohio</li>
   <li id="state-oklahoma" name="OK">Oklahoma</li>
   <li id="state-oregon" name="OR">Oregon</li>
   <li id="state-pennsylvania" name="PA">Pennsylvania</li>
   <li id="state-rhode island" name="RI">Rhode Island</li>
   <li id="state-south carolina" name="SC">South Carolina</li>
   <li id="state-south dakota" name="SD">South Dakota</li>
   <li id="state-tennessee" name="TN">Tennessee</li>
   <li id="state-texas" name="TX">Texas</li>
   <li id="state-utah" name="UT">Utah</li>
   <li id="state-virginia" name="VA">Virginia</li>
   <li id="state-vermont" name="VT">Vermont</li>
   <li id="state-washington" name="WA">Washington</li>
   <li id="state-wisconsin" name="WI">Wisconsin</li>
   <li id="state-west virginia" name="WV">West Virginia</li>
   <li id="state-wyoming" name="WY">Wyoming</li>
</ul>
<div id="featured-schools"></div></div>
			</div>
        </div>
		<div class="footer-wrap clear-block">		<footer id="footer">
			<section class="container">
				<p>Copyright &copy 2014 Vantage Media, LLC - <a href="http://www.vantagemedia.com/privacy-policy/">Privacy Policy</a></p>
			</section>
		</footer></div>
    </div>

  </div>

  
  
</div>
  </div>
</div>
  </div>

  </div>    <div class="region region-page-bottom">
    <script type="text/javascript" language="JavaScript" src="//images.vantage-media.net/d//sites/default/files/assets/sitecatalyst/cookies_manager.js"?n9jkwa"></script>
<!-- SiteCatalyst code version: H.26.
Copyright 1996-2014 Adobe, Inc. -->
<script type="text/javascript" language="JavaScript" src="//images.vantage-media.net/d//sites/default/files/assets/sitecatalyst/prod/s_code.js?n9jkwa"></script>
<script type="text/javascript" language="JavaScript"><!--
(function() { 
var vm_tracking = (typeof Drupal.settings.Vantage === 'object') ? Drupal.settings.Vantage : false; 
var domainSpecificReferrers = ["yahoo.com","www.yahoo.com","ca.yahoo.com","news.yahoo.com","hotjobs.yahoo.com","finance.yahoo.com","financiallyfit.yahoo.com","associatedcontent.com","www.associatedcontent.com","att.my.yahoo.com"]; 
var domainSpecificKid = "EZPI"; 
function getURLParameter(name) { 
return decodeURIComponent((new RegExp("[?|&]" + name + "=" + "([^&;]+?)(&|#|;|$)").exec(location.search)||[,""])[1].replace(/\+/g, "%20"))||null; 
} 
function getReferrerParameter(name) { 
var referrerURL=document.referrer; 
if (referrerURL != null && referrerURL.length > 0) { 
var query=referrerURL.substring(referrerURL.indexOf("?"), referrerURL.length); 
if (query != null && query.length > 0) { 
return decodeURIComponent((new RegExp("[?|&]" + name + "=" + "([^&;]+?)(&|#|;|$)").exec(query)||[,""])[1].replace(/\+/g, "%20"))||null; 
} 
} 
return null; 
} 
function getDrupalPostParameter(parameter){ 
if(Drupal.settings.Vantage.parameters !== undefined){ 
var p = Drupal.settings.Vantage.parameters; 
if(p[parameter] !== undefined && p[parameter]){ 
return p[parameter]; 
} 
} 
return ""; 
} 
function getSrcKid(){ 
var validSrcValues= ["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16"]; 
var srcKid = getURLParameter("srcKid"); 
if(srcKid === null || srcKid === undefined || srcKid.length == 0){ 
srcKid = getDrupalPostParameter("srcKid"); 
}  
if (srcKid === undefined || !srcKid || srcKid == null || srcKid.length == 0) { 
var kidVal = jQuery("[name=srcKid]").val(srcKid); 
} 
/*if (srcKid === undefined || !srcKid || srcKid == null || srcKid.length == 0) { 
srcKid = getCookie("srcKid"); 
}*/ 
if (srcKid === undefined || !srcKid || srcKid == null || srcKid.length == 0 || jQuery.inArray(srcKid, validSrcValues) < 0) { 
if(kid == vm_tracking.tracking_parameters["natural_search_kid"]){ 
srcKid = "7"; 
}else if(kid == vm_tracking.tracking_parameters["type_in_kid"]){ 
srcKid = "6"; 
}else{ srcKid = null; } 
}  
if (srcKid !== undefined && srcKid && srcKid != null && srcKid.length > 0) { 
//saveCookie("srcKid", srcKid, 1); 
var srcKidVal = jQuery("[name=srcKid]").val(srcKid); 
} 
return srcKid;   
} 
function getTypeKid(){ 
var validTypeValues = ["0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19","20","21","22","23","24","25","26","27","28","29","30","31","32","33","34","35","36","37","38","39","40","41","42","43","44","45","46","47","48","49","50","51","52","53","54","55","56","57","58"]; 
var typeKid = getURLParameter("typeKid"); 
if(typeKid === null || typeKid === undefined || typeKid.length == 0){ 
typeKid = getDrupalPostParameter("typeKid"); 
} 
if (typeKid === undefined || !typeKid || typeKid == null || typeKid.length == 0) { 
typeKid = jQuery("[name=typeKid]").val(typeKid); 
} 
if (typeKid === undefined || !typeKid || typeKid == null || typeKid.length == 0 || jQuery.inArray(typeKid, validTypeValues) < 0) { 
if(kid == vm_tracking.tracking_parameters["natural_search_kid"]){ 
typeKid = "18"; 
}else if(kid == vm_tracking.tracking_parameters["type_in_kid"]){ 
typeKid = "14"; 
}else{ typeKid = null; } 
} 
/*if (typeKid === undefined || !typeKid || typeKid == null || typeKid.length == 0) { 
typeKid = getCookie("typeKid"); 
}*/ 
if (typeKid !== undefined && typeKid && typeKid != null && typeKid.length > 0) { 
//saveCookie("typeKid", typeKid, 1); 
var typeKidVal = jQuery("[name=typeKid]").val(typeKid); 
} 
return typeKid; 
} 
function getKid() { 
var kid = getURLParameter("kid"); 
if (kid === undefined || !kid || kid == null || kid.length == 0) { 
kid = getURLParameter("svkid"); 
} 
if (kid === undefined || !kid || kid == null || kid.length == 0) { 
kid = vm_tracking.parameters["kid"]; 
} 
if ((kid === undefined || !kid || kid == null || kid.length == 0) && typeof document.referrer !== "undefined" && document.referrer !== undefined && document.referrer != null && document.referrer.length > 0) { 
kid = getReferrerParameter("kid"); 
if (kid === undefined || !kid || kid == null || kid.length == 0) { 
kid = getReferrerParameter("svkid"); 
} 
} 
if (kid === undefined || !kid || kid == null || kid.length == 0) { 
kid = getCookie("kid"); 
} 
if ((kid === undefined || !kid || kid == null || kid.length == 0) && typeof document.referrer !== "undefined" && document.referrer !== undefined && document.referrer != null && document.referrer.length > 0) { 
if (document.referrer.match(/:\/\/(.[^/]+)/) != null) { 
var refNoProtocol = document.referrer.match(/:\/\/(.[^/]+)/)[1]; 
} else { 
var refNoProtocol = document.referrer; 
} 
var domainRef = refNoProtocol.substring(0, refNoProtocol.indexOf("?")); 
if (typeof domainSpecificReferrers !== "undefined" && domainSpecificReferrers !== undefined && domainSpecificReferrers && domainSpecificReferrers.length > 0 && typeof domainSpecificKid !== "undefined" && domainSpecificKid !== undefined && domainSpecificKid && domainSpecificKid.length > 0 && jQuery.inArray(domainRef, domainSpecificReferrers) > -1) { 
kid = domainSpecificKid; 
} 
if (kid === undefined || !kid || kid == null || kid.length == 0) { 
//natural search 
kid = vm_tracking.tracking_parameters["natural_search_kid"]; 
} 
} 
if (kid === undefined || !kid || kid == null || kid.length == 0) { 
//type in 
kid = vm_tracking.tracking_parameters["type_in_kid"]; 
} 
if (kid !== undefined && kid && kid != null && kid.length > 0) { 
saveCookie("kid", kid, 1); 
var kidVal = jQuery("[name=kid]").val(kid); 
} 
return kid; 
} 
kid = getKid(); 
window.srcKid = getSrcKid(); 
window.typeKid = getTypeKid(); 
function getAdSource() { 
var adSource = getURLParameter("adsource"); 
if (adSource === undefined || !adSource || adSource == null || adSource.length == 0) { 
adSource = vm_tracking.parameters["adsource"]; 
} 
if ((adSource === undefined || !adSource || adSource == null || adSource.length == 0) && typeof document.referrer !== "undefined" && document.referrer !== undefined && document.referrer != null && document.referrer.length > 0) { 
adSource = getReferrerParameter("adsource"); 
if (adSource === undefined || !adSource || adSource == null || adSource.length == 0) { 
adSource = getReferrerParameter("adsource"); 
} 
} 
if (adSource === undefined || !adSource || adSource == null || adSource.length == 0) { 
adSource = jQuery("[name=adSource]").val(); 
} 
if (adSource === undefined || !adSource || adSource == null || adSource.length == 0) { 
adSource = getCookie("adsource"); 
}  
if (adSource !== undefined && adSource && adSource != null && adSource.length > 0) { 
saveCookie("adsource", adSource, 1); 
var adSourceVal = jQuery("[name=adSource]").val(adSource); 
} 
return adSource; 
} 
window.adSource = getAdSource(); 
var debug = false; 
include_js = function(file) { 
var html_doc = document.getElementsByTagName('head')[0]; 
var js = document.createElement('script'), 
done = false; 
js.setAttribute('type', 'text/javascript'); 
js.setAttribute('src', file); 
try { 
html_doc.appendChild(js); 
} catch (ex) { 
if (debug && window.console !== undefined) { 
console.log('Debug: Warning! Request for ' + file + ' failed. Reason: ' + ex); 
} 
} 
js.onload = js.onreadystatechange = function() { 
if (!done && (!this.readyState || this.readyState === "loaded" || this.readyState === "complete")) { 
done = true; 
js.onload = js.onreadystatechange = null; 
} 
}; 
return false; 
}; 
if (typeof(setOverrideFunnelStart) !== 'undefined' && typeof(setOverrideFunnelStart) 
=== 'function') { 
setOverrideFunnelStart(); 
}
var fieldUser = jQuery("[name=userId]").val(); 
var fieldInteraction = jQuery("[name=interactionId]").val(); 
fieldInteraction = (fieldInteraction === undefined || !fieldInteraction || fieldInteraction.lenght == 0) ? fieldInteraction : jQuery("[name=field_interaction_id]").val(); 
var currentUser = (fieldUser !== undefined && fieldUser && fieldUser.lenght > 0) ? fieldUser : getCookie("_VMU"); 
var currentInteraction = (fieldInteraction !== undefined && fieldInteraction && fieldInteraction.lenght > 0) ? fieldInteraction : getCookie("_VMI"); 
if (currentUser === undefined || !currentUser || currentUser.length == 0 || currentInteraction === undefined || !currentInteraction || currentInteraction.length == 0 ||(vm_tracking && vm_tracking.tracking_parameters["funnel_start"] == 1) || (window.override_funnel_start !== undefined && window.override_funnel_start == 1)) { 
currentUser = (currentUser != null && currentUser != "") ? "&UserId=" + currentUser : "" ; 
var utsUrl = "//marketplaces.vantagemedia.com/ut/json?callback=scTracking" + currentUser; 
include_js(utsUrl); 
} else { 
scTracking(null); 
} 
})(); //-->
</script><script language="JavaScript" type="text/javascript"><!--
if(navigator.appVersion.indexOf('MSIE')>=0)document.write(unescape('%3C')+'\!-'+'-')
//--></script><noscript><a href="http://www.omniture.com" title="Web Analytics"><img src="http://vantagemedia1.d1.sc.omtrdc.net/b/ss/vantagemediadev/1/H.26--NS/0/7743596"
height="1" width="1" border="0" alt="" /></a></noscript><!--/DO NOT REMOVE/-->
<!-- End SiteCatalyst code version: H.26. -->
  </div>

</body>
</html>

因为www.hust.edu.cn这个域名,在实际访问的过程中,重定向到www.hust.edu.cn/home这个域名,pos请求方式不会自动重定向,需要根据返回值进行判断

改进Post方式的的代码如下:

<pre name="code" class="java">package com.tds.commons;

import java.io.IOException;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;

/**
 * http post方式
 * 
 * @author Administrator
 * 
 */
public class HttpPostTest {

	public static void main(String[] args) {

		// 构造HttpClient的实例
		HttpClient httpClient = new HttpClient(); // 3.1版本
		// 创建post方法的实例
		PostMethod postMethod = new PostMethod("http://www.hust.edu.com");
		// 使用系统提供的默认的恢复策略
		postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
		try {
			// 执行postMethod
			int statusCode = httpClient.executeMethod(postMethod);
			if (statusCode != HttpStatus.SC_OK) {
				System.err.println("Method failed: " + postMethod.getStatusLine());
				if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) {
					// 从头中取出转向的地址
					Header locationHeader = postMethod.getResponseHeader("location");
					String location = null;
					if (locationHeader != null) {
						location = locationHeader.getValue();
						System.out.println("The page was redirected to:" + location);
						// 	先释放
						postMethod.releaseConnection();
						postMethod = new PostMethod(location);
						statusCode = httpClient.executeMethod(postMethod);
						if (statusCode == HttpStatus.SC_OK) {
							System.out.println(postMethod.getResponseBodyAsString());
						}
					} else {
						System.err.println("Location field value is null.");
					}
					postMethod.releaseConnection();
					return;
				}
			}
			// 读取内容
			byte[] responseBody = postMethod.getResponseBody();
			// 处理内容
			System.out.println(new String(responseBody));
		} catch (HttpException e) {
			// 发生致命的异常,可能是协议不对或者返回的内容有问题
			System.out.println("Please check your provided http address!");
			e.printStackTrace();
		} catch (IOException e) {
			// 发生网络异常
			e.printStackTrace();
		} finally {
			// 释放连接
			postMethod.releaseConnection();
		}
	}
}
从运行的结果可以看,只有这样,才能和Head方式返回的结果一样

 其实的请求方法如 
HEAD     
PUT      
DELETE     
TRACE    
CONNECT   
OPTIONS 用法也差不多,有兴趣可以自己试着去做一下相关的实验 






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值