重点是
- 字符集
- 请求返回类似于流的一次性
package xyz.tangzekk.mydaliynote.M5.D28;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
import java.io.IOException;
public class MyHttpClientM5D28 {
@Test
public void test1() throws IOException {
int timeout = 5;
RequestConfig config = RequestConfig.custom().
setConnectTimeout(timeout * 1000)
.setConnectionRequestTimeout(timeout * 1000)
.setSocketTimeout(timeout * 1000).build();
/**
* 创建一个HttpClient(只能用一次??) 所以不用close,可以进行多样化设置
*/
CloseableHttpClient httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
// 网上模拟接口的一个网站简单用用可以,吃过他的苦头,不建议正式用
String url = "https://www.easy-mock.com/mock/5cece114aa922e57a46708ff/hj/getUser";
HttpPost post = new HttpPost(url);
/**
* client可以设置,单次请求也可以设置选项..这里注释了
*/
// RequestConfig config1 = RequestConfig.custom().setConnectTimeout(2).build();
post.setHeader("cool", "you so cool");
// 添加post的body,这里随便传个json对象,异常先不管
String postJson = new ObjectMapper().writeValueAsString(new HelloM5D28("aa", "bb"));
/**
* 把json传入Entity里,注意一定一定一定一定一定一定一定一定一定一定一定一定要设字符集,不然中文就是??????????????????????
*/
StringEntity entity = new StringEntity(postJson, "utf-8");
post.setEntity(entity);
/**
* 这个Response对象也是用一次就失效 不用close,开始发起请求,异常不管
*/
CloseableHttpResponse response = httpClient.execute(post);
/**
* 转换一下取得对象
*/
User user = new ObjectMapper().readValue(response.getEntity().getContent(), User.class);
System.out.println(user);// User(name=tom, age=22, parent=User.ParentBean(dad=tomdd, mum=tommum), score=[10, 30, 15])
// 如果接受的不要转成json 收成String
String s1 = EntityUtils.toString(response.getEntity());
// 操作这个String
JsonNode jsonNode = new ObjectMapper().readTree(s1);
if (jsonNode.isArray()) {
System.out.println("...");
}
if (jsonNode.isObject()) {
System.out.println("...");
}
// GOOD
}
}
jackson 真的是个好东西 值得慢慢品味,阿里巴巴什么法斯特接僧下辈子比得过他吧,jackson单看jar包就能懂了 一行代码有的能有十行的注释,谁都看得懂.