import org.apache.http.client.fluent.Form;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.fluent.Response;
import java.io.IOException;
/**
* 访问API接口通用的做法。
* 主要使用apache提供的一个便捷工具类,http.client.fluent
* 访问API接口的时候首先涉及到登陆,那就首先登陆
* 然后开始CRUD操作,涉及Get和Post请求两种请求方式
*
* */
public class HttpRequest {
public static void main(String[] args) throws IOException {
//1、登陆
Response res = Request.Post("http://192.168.253.3:8081")
.bodyForm(Form.form()
.add("action", "login")
.add("username", "azkaban")
.add("password", "azkaban").build())
.execute();
//2、Get方式请求 并 获取返回值
String str2 = "http://192.168.253.3:8081/manager?ajax=fetchProjectLogs&project=my_test&session.id=";
Request get = Request.Get(str2);
Response execute = get.execute();
String content = execute.returnContent().toString();
System.out.println(content);
//3、Post方式请求并返回值
Response execute1 = Request.Post("http://192.168.253.3:8081/manager")
.bodyForm(Form.form()
.add("action", "create")
.add("session.id", "")
.add("name", "test_jjk")
.add("description", "xixi").build()).execute();
String s = execute1.returnContent().toString();
System.out.println(s);
//Post访问
Request res1 = Request.Post("http://192.168.253.3:8081/manager")
.bodyForm(Form.form()
.add("session.id", "")
.add("action", "create")
.add("name", "my_test2")
.add("description", "haha").build());
res1.execute();
//Get访问
String str = "http://192.168.253.3:8081/manager?delete=true&project=my_test2&session.id=";
Request.Get(str).execute();
}
}
}
================================下面示例对应上面的代码=======================================
get请求示例: 其实就是拼接字符串,按上面的要求
post请求: 把请求体放在一个地方,然后执行
本文详细介绍如何使用Apache HttpClient库进行HTTP请求,包括登录、GET和POST请求的实现,以及如何解析响应内容。
2万+

被折叠的 条评论
为什么被折叠?



