HttpClient模拟登陆问题请教
想通过HttpClient 4.2.5 来模拟登陆,进行接口调用,如想调用一个接口,这个接口是获取云盘信息,但是这个接口的前提条件是必须要登陆,所以我写了2个步骤,1是登陆云盘,2是登陆后调用获取云盘信息的接口HttpClient httpclient = new DefaultHttpClient();
HttpPost post = new HttpPost(
"http://localhost:8080/pan-api/login/clientLogin");
List<NameValuePair> formParams = new ArrayList<NameValuePair>();
formParams.add(new BasicNameValuePair("uid", "test@gmail.com"));
formParams.add(new BasicNameValuePair("pwd", "test"));
HttpEntity entity = new UrlEncodedFormEntity(formParams, "UTF-8");
post.setEntity(entity);
HttpResponse response = httpclient.execute(post);
System.out.println("Login form get: " + response.getStatusLine());
String body = EntityUtils.toString(response.getEntity());
System.out.println("Response Body:" + body);
=================第一次登陆结束,从返回结果来看,是登陆成功的======================
HttpPost post2 = new HttpPost(
"http://localhost/pan-api/login/space");
HttpResponse response2 = httpclient.execute(post2);
String body2 = EntityUtils.toString(response2.getEntity());
System.out.println("Response Body:" + body2);
=================第二次登陆结束,从返回结果来看,总是提示“请先登陆在操作”=========
【跪求】请问怎么破啊? Java HttpClient 接口调用 --------------------编程问答-------------------- 网上的例子看看
public class FormLoginDemo {
static final String LOGON_SITE = "localhost" ;
static final int LOGON_PORT = 8080;
public static void main(String[] args) throws Exception{
HttpClient client = new HttpClient();
client.getHostConfiguration().setHost(LOGON_SITE, LOGON_PORT);
// 模拟登录页面 login.jsp->main.jsp
PostMethod post = new PostMethod( "/main.jsp" );
NameValuePair name = new NameValuePair( "name" , "ld" );
NameValuePair pass = new NameValuePair( "password" , "ld" );
post.setRequestBody( new NameValuePair[]{name,pass});
int status = client.executeMethod(post);
System.out.println(post.getResponseBodyAsString());
post.releaseConnection();
// 查看 cookie 信息
CookieSpec cookiespec = CookiePolicy.getDefaultSpec();
Cookie[] cookies = cookiespec.match(LOGON_SITE, LOGON_PORT, "/" , false , client.getState().getCookies());
if (cookies.length == 0) {
System.out.println( "None" );
} else {
for ( int i = 0; i < cookies.length; i++) {
System.out.println(cookies[i].toString());
}
}
// 访问所需的页面 main2.jsp
GetMethodget=newGetMethod("/main2.jsp");
client.executeMethod(get);
System.out.println(get.getResponseBodyAsString());
get.releaseConnection();
}
}
补充:Java , Web 开发