---
title: "使用Apache HttpClient访问ASP.NET发送GET和POST请求"
author: "zywang"
date: "2011-02-22T17:41:36Z"
tags: []
categories: ["编程语言"]
slug: "apache-httpclient-asp-net-get-post"
draft: false
lastmod: "2011-02-23T12:23:37Z"
id: 916846
url: "https://zywang.iteye.com/blog/916846"
---

预备知识请查看[使用Apache HttpClient访问JSP发送GET和POST请求](/blog/916834)

 

这里主要介绍对于ASP的访问的一点需要注意的地方。

1、访问ASP.NET网站时，需要请求的上下文，即必须保证HttpClient不能被关闭（也许这是必须的）;

2、发送POST请求时，需要根据上一次请求时从服务器端带过来的隐藏域数据，也就是：\_\_PREVIOUSPAGE、\_\_EVENTVALIDATION、\_\_VIEWSTATE，或者还有其它的，创建表单时要把他们（如果有的话）都填进去;

3、你需要使用HttpWatch查看一下IE的发送数据，找到你要点的按钮（MS根据按钮的名称判断进谁的事件，猜测的...）；

 

Apache HttpClient 版本 4.0.3

下载地址：[http://hc.apache.org/downloads.cgi](http://hc.apache.org/downloads.cgi)

 

```
package com.zywang.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

public class HttpClientForAspx {
	private static Map<String, String> params = null; 
	private static String loginPage = "http://localhost/kaoqin";
	private static String defaultPage = "http://localhost/kaoqin/Default.aspx";
	private static String indexPage = "http://localhost/kaoqin/Index.aspx";
	private static String userName = "zywang";
	private static String password = "zywang";
	
	//.Net隐藏域
	private final static String PREVIOUSPAGE = "__PREVIOUSPAGE";
	private final static String EVENTVALIDATION = "__EVENTVALIDATION";
	private final static String VIEWSTATE = "__VIEWSTATE";
	
	public static void main(String[] args)
			throws ClientProtocolException, IOException {
		attendance("下班操作");
	}

	/**
	 * 运行按钮功能
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	private static void attendance(String btnValue)
			throws IOException, ClientProtocolException {
		HttpClient client = new DefaultHttpClient();
		//打开主页
		if(!loadPage(client ,loginPage)){
			System.out.println("打开主页失败！");
			return;
		}
		//执行登录
		if(loginPost(client)){
			//打开主页面
			if(loadPage(client,indexPage)){
				//开始打开          上班操作          下班操作
				if(sign(client,btnValue)){
					System.out.println("操作成功！");
				}else{
					System.out.println("操作失败！");
				}
			}
		}else{
			System.out.println("登录失败！");
		}
		client.getConnectionManager().shutdown();
	}

	/**
	 * 根据按钮名称进行操作
	 */
	private static boolean sign(HttpClient client,String btnValue)
			throws IOException,
			ClientProtocolException {
//		System.out.println("==>>开始操作");
		HttpPost post = new HttpPost(indexPage);
		List<NameValuePair> qparams = new ArrayList<NameValuePair>();
		qparams.add(
				new BasicNameValuePair(PREVIOUSPAGE, params.get(PREVIOUSPAGE)));
		qparams.add(
				new BasicNameValuePair(EVENTVALIDATION, params.get(EVENTVALIDATION)));
		qparams.add(
				new BasicNameValuePair(VIEWSTATE, params.get(VIEWSTATE)));
		//包含目标按钮则执行操作
		if(getKeyByValue(btnValue)!=null){
			qparams.add(new BasicNameValuePair(getKeyByValue(btnValue), btnValue));
			post.setEntity(new UrlEncodedFormEntity(qparams));
			HttpResponse response = client.execute(post);
			int statusCode = response.getStatusLine().getStatusCode();
			System.out.println("statusCode:"+statusCode);
			post.abort();
			return true;
		}
		System.out.println("没有发现按钮:["+btnValue+"]");
		post.abort();
		return false;
	}

	/**
	 * 登录系统
	 */
	private static boolean loginPost(HttpClient client) throws IOException,
			ClientProtocolException {
//		System.out.println("==>>开始登录");
		HttpPost post = new HttpPost(defaultPage);
		List<NameValuePair> qparams = new ArrayList<NameValuePair>();
		qparams.add(
				new BasicNameValuePair(EVENTVALIDATION, params.get(EVENTVALIDATION)));
		qparams.add(new BasicNameValuePair(VIEWSTATE, params.get(VIEWSTATE)));
		qparams.add(new BasicNameValuePair("imgBtnLogin.x", "0"));
		qparams.add(new BasicNameValuePair("imgBtnLogin.y", "0"));
		qparams.add(new BasicNameValuePair("txtUser", userName));
		qparams.add(new BasicNameValuePair("txtPassword", password));
		post.setEntity(new UrlEncodedFormEntity(qparams));
		HttpResponse response = client.execute(post);
		int statusCode = response.getStatusLine().getStatusCode();
		System.out.println("statusCode:"+statusCode);
		if(statusCode == 302){
			post.abort();
			return true;
		}
		post.abort();
		return false;
	}

	/**
	 * 加载页面-通过GET方式
	 */
	private static boolean loadPage(HttpClient client,String url)
			throws IOException,
			ClientProtocolException {
//		System.out.println("==>>加载页面(GET):"+url);
		HttpGet get = new HttpGet(url);
		HttpResponse response = client.execute(get);
		int statusCode = response.getStatusLine().getStatusCode();
		System.out.println("statusCode:"+statusCode);
		HttpEntity entity = response.getEntity();
		BufferedReader reader = new BufferedReader(
				new InputStreamReader(entity.getContent()));
		String buffer = null;
		StringBuilder sb = new StringBuilder();
		while((buffer=reader.readLine())!=null){
			sb.append(buffer);
		}
		params = getAllInputNames(sb.toString());
		get.abort();
		return statusCode == 200;
	}
	
	private static String getInputProperty(String input,String property) {
		Matcher m = Pattern.compile(property+"[\\s]*=[\\s]*\"[^\"]*\"").matcher(input);
		if(m.find()){
			String v = m.group();
			return v.substring(v.indexOf("\"")+1,v.length()-1);
		}
		return null;
	}
	
	private static Map<String, String> getAllInputNames(String body){
		Map<String, String> parameters = new HashMap<String, String>();
		Matcher matcher = Pattern.compile("<input[^<]*>").matcher(body);
		while(matcher.find()){
			String input = matcher.group();
			if(input.contains("name")){
				parameters.put(getInputProperty(input,"name"), 
						getInputProperty(input,"value"));
			}
		}
		return parameters;
	}
	
	private static String getKeyByValue(String value){
		for(String s:params.keySet()){
			if(params.get(s).equals(value)){
				return s;
			}
		}
		return null;
	}
}
```