HttpClient,实现登录,请求等操作,session保持
来源:技术人生 责任编辑:栏目编辑 发表时间:2013-07-02 03:41 点击:次
HttpClient,httpclient.jar包中的,我则喜欢折射成类似于dll以用的形式,知道在哪个namespace下
http://hc.apache.org/httpcomponents-client
可以从这里获取或得到些信息
实现的目标:
1.模拟登录
2.登录之后,模拟提交请求
关键点:
1.session状态保持
2.页面隐藏的属性获取
之前用HttpURLConnection,但未成功,瓶颈在于没有绕过session保持上,最终还是使用HttpClient,实现相对容易些
示例代码
(代码有删减,不见得能够跑通,需要修改)
/** * */package httpclienttest;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.File;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;import java.util.ArrayList;import java.util.Date;import java.util.List;import java.util.Random;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.ResponseHandler;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.cookie.Cookie;import org.apache.http.impl.client.BasicResponseHandler;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.message.BasicNameValuePair;import org.apache.http.protocol.HTTP;import com.alibaba.ccbu.parseelements.ParseTest;/** * @author forward * */public class LoginFormDemo { public static void DemoLoginTwo() throws Exception { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet( http://xxxx.com/xx.htm); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); System.out.println("Login form get: " + response.getStatusLine()); if (entity != null) { entity.consumeContent(); } System.out.println("Initial set of cookies:"); List<Cookie> cookies = httpclient.getCookieStore().getCookies(); if (cookies.isEmpty()) { System.out.println("None"); } else { for (int i = 0; i < cookies.size(); i++) { System.out.println("- " + cookies.get(i).toString()); } } // action=xxx&Password=xxxx HttpPost httpost = new HttpPost( "http://localhost/sss"); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); nvps.add(new BasicNameValuePair("LoginId", "xxxx")); nvps.add(new BasicNameValuePair("Password", "xxxxx")); nvps.add(new BasicNameValuePair("action", "xxxx")); nvps.add(new BasicNameValuePair("eventSubmit_doPost", "xxxx")); httpost.setEntity
相关新闻>>
最新推荐更多>>>
- 发表评论
-
- 最新评论 更多>>