Java使用HttpClient发送请求的几种常用方式

阅读更多

使用的jar包有3个,Maven中添加以下依赖:

commons-httpclient

commons-httpclient

3.1

commons-logging

commons-logging

1.2

commons-codec

commons-codec

1.9

1第一种:普通的Get/Post请求,Get请求可以带参数(无需登陆)

public static String GetHtttpLink(String path) throws Exception {

HttpClient client = new HttpClient();// 打开新窗口

GetMethod get = new GetMethod(path);//path是请求地址,可以带参数

int st1 = client.executeMethod(get);

logger.info("执行状态:" + st1);

String result = get.getResponseBodyAsString();//服务端返回的Response

get.releaseConnection();//释放链接

return result;

}

public static String PostHtttpLink(String path) throws Exception {

HttpClient client = new HttpClient();// 打开新窗口

PostMethod po = new PostMethod(path);

int st1 = client.executeMethod(po);

logger.info("执行状态:" + st1);

String result = po.getResponseBodyAsString();//服务端返回的Response

po.releaseConnection();

return result;

}

第二种:带多个参数的Post请求 (无需登陆)

public static String PostWithParas() {

HttpClient client = new HttpClient();

PostMethod postMethod = new PostMethod("http://127.0.0.1:8080/userrz");

NameValuePair param1 = new NameValuePair("id", "XXX");//参数1

NameValuePair param2 = new NameValuePair("time", "XXXXXX");//参数2

NameValuePair param3 = new NameValuePair("url", "XXXXXX");//参数3

NameValuePair param4 = new NameValuePair("msg", "XXX");参数4 postMethod.setRequestBody(new NameValuePair[]{param1, param2, param3, param4 });//设置参数

String result="";

try {

client.executeMethod(postMethod);//执行请求

result = postMethod.getResponseBodyAsString();//获取返回的Response

} catch (IOException e) {

e.printStackTrace();

}

postMethod.releaseConnection();//释放链接

}

第三种:带Cookies请求认证,访问网站内部某个页面(需要登陆,用户名密码认证)

public static String GetLink(String Corpcode, String Code) throws Exception {

HttpClient client = new HttpClient();// 打开新窗口

client.getHostConfiguration().setHost("localhost", 8080);// 配置

// 模拟手动登录页面,login是处理登陆的action

PostMethod post = new PostMethod("/login");

NameValuePair username = new NameValuePair("username", "admin");//用户名

NameValuePair pass = new NameValuePair("password", "admin123");//密码

post.setRequestBody(new NameValuePair[] { username, pass });

int status = client.executeMethod(post);

System.out.println("执行状态:" + status + ",返回状态:" + post.getStatusLine(); post.releaseConnection();

// 查看 cookie,并传递Cookies到服务器认证

CookieSpec cookiespec = CookiePolicy.getDefaultSpec();

Cookie[] cookies = cookiespec.match("localhost", 8080, "/", false, client.getState().getCookies());

if (cookies.length == 0) {

System.out.println("没有Cookies");

} else {

for (int i = 0; i < cookies.length; i++) {

System.out.println("Cookies:" + cookies[i].toString());

}

}

// 因为前面已经登陆了,也加入了Cookies,所以才可以直接访问这个地址

GetMethod get = new GetMethod("/user");//这个才是需要访问的真正action

int stats = client.executeMethod(get);

String result = get.getResponseBodyAsString();

System.out.println("Get请求:" + result);

get.releaseConnection();

return result;

}

你可能感兴趣的:(Java使用HttpClient发送请求的几种常用方式)