HttpClient模拟登陆
public static void testPost(int index) throws Exception{
HttpClient client = new HttpClient();
//登录
PostMethod post = new PostMethod("登录提交路径");
NameValuePair name = new NameValuePair("name", "sysadmin");
NameValuePair pass = new NameValuePair("password", "123123");
NameValuePair action = new NameValuePair("action", "in");
post.setRequestBody(new NameValuePair[] { name, pass, action });
client.executeMethod(post);
//释放连接,以免超过服务器负荷
post.releaseConnection();
//访问之前需要登录的接口,即要访问数据要先登录
GetMethod get = new GetMethod("接口URL");
HttpMethodParams params = new HttpMethodParams();
//设置编码格式,以防中文乱码
params.setContentCharset("UTF-8");
get.setParams(params);
client.executeMethod(get);
System.out.println(get.getResponseBodyAsString());
//释放连接,以免超过服务器负荷
get.releaseConnection();
}
相关推荐
创建一个 HttpClient 实例,这个实例需要调用 Dispose 方法释放资源,这里使用了 using 语句。接着调用 GetAsync,给它传递要调用的方法的地址,向服务器发送 Get 请求。