Apache HttpClient之fluent API的使用
时间:2017-11-21 14:23:54
收藏:0
阅读:2621
该方法为Apache HttpClient 4.5以上的版本支持,在官网有明确的说明。
对比以前的方式,其优点是代码更简洁,同时为线程安全的。仅举一个最简单的post栗子
JAR包信息:
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.1</version>
</dependency>
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();
}
}
评论(0)