Apache HttpClient之fluent API的使用
2021-04-26 21:29
标签:intel dmi manage lte pcl tty apache pac ted 该方法为Apache HttpClient 4.5以上的版本支持,在官网有明确的说明。 JAR包信息: 测试代码: Apache HttpClient之fluent API的使用 标签:intel dmi manage lte pcl tty apache pac ted 原文地址:http://www.cnblogs.com/hailongchen/p/7872491.html
对比以前的方式,其优点是代码更简洁,同时为线程安全的。仅举一个最简单的post栗子
package utils;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.client.fluent.Request;
import org.apache.http.entity.ContentType;
import java.io.IOException;
/**
* Created with IntelliJ IDEA.
* Description:
* Http请求工具类
*
* @author
* Date: 2017-11-01
* Time: 10:24
*/
public class HttpClientUtil {
/**
* @return String
* 响应体
*/
public String jsonPostHttp(JSONObject jsonObject, String url) throws IOException {
String response = Request.Post(url).bodyString(jsonObject.toString(), ContentType.APPLICATION_JSON).execute().returnContent().asString();
System.out.println(response); // 将返回的内容打印出来便于调试
return response;
}
}
package utilsTest;
import com.alibaba.fastjson.JSONObject;
import org.junit.Test;
import utils.HttpClientUtil;
import java.io.File;
import java.io.IOException;
public class HttpClientUtilTest {
@Test
public void httpClientUtilTest(){
JSONObject jsonObject = new JSONObject();
// 根据业务需要,定义JSONObject所需的参数
jsonObject.put("appId", "1");
jsonObject.put("userName", "admin");
jsonObject.put("password", "111111");
HttpClientUtil httpClientUtil = new HttpClientUtil();
try {
httpClientUtil.jsonPostHttp(jsonObject,"http://localhost/manage/auth/login.do");
} catch (IOException e) {
e.printStackTrace();
}
}
文章标题:Apache HttpClient之fluent API的使用
文章链接:http://soscw.com/index.php/essay/79911.html