Send HTTP request, call third-party interface
Introduce dependencies:
<!-- 引入http-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
This is what you need to share when you need to call the three-party interface to get data when you are doing a project:
- application/x-www-form-urlencoded 方式
/**
* 发送http POST请求
* @param parameter为请求参数
* @return 远程响应结果
*/
public static String sendPunlic2GPost(String parameter) {
log.info("--------begin--------");
// 发送请求的URL
String url = "请求地址";
// 编码格式
String charset = "UTF-8";
// 请求内容
String content = parameter;
log.info(content);
// 使用帮助类HttpClients创建CloseableHttpClient对象.
CloseableHttpClient client = HttpClients.createDefault();
// HTTP请求类型创建HttpPost实例
HttpPost post = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(1000)
.setSocketTimeout(5000).build();
post.setConfig(requestConfig);
// 使用addHeader方法添加请求头部,诸如User-Agent, Accept-Encoding等参数.
//请求中的媒体类型--
post.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
// 组织数据
StringEntity se;
String resData = null;
try {
se = new StringEntity(content);
// 设置编码格式
se.setContentEncoding(charset);
// 设置数据类型
se.setContentType("application/json");
// 对于POST请求,把请求体填充进HttpPost实体.
post.setEntity(se);
// 通过执行HttpPost请求获取CloseableHttpResponse实例
// ,从此CloseableHttpResponse实例中获取状态码,错误信息,以及响应页面等等.
CloseableHttpResponse response;
try {
response = client.execute(post);
// 通过HttpResponse接口的getEntity方法返回响应信息,并进行相应的处理?
HttpEntity entity = response.getEntity();
resData = EntityUtils.toString(response.getEntity());
System.out.println(resData);
// 最后关闭HttpClient资源.
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
log.info("--------end--------");
//返回的数据资源
return resData;
}
-
application/json;charset=UTF-8
Modify the above-the media type in the request-this step to:
post.setHeader("Content-Type", "application/json;charset=UTF-8"); -
Analysis and acquisition of the return value:
String resData = sendPunlic2GPost(String parameter);
JSONObject jsStr = JSONObject.parseObject(operateDeviceOpen);
code = jsStr.getString("code");
//以此内推获取所需要返回的值
Two more: The
above can see that the returned json string is converted to a json object, let ’s talk about the json字符串转为Java
object below
Way 1:
public static <T> T string2Obj(String str, Class<T> clazz){
if(StringUtils.isEmpty(str) || clazz == null){
return null;
}
try {
return clazz.equals(String.class)? (T)str : objectMapper.readValue(str, clazz);
} catch (Exception e) {
log.warn("Parse String to Object error",e);
return null;
}
}
Basic type conversion:
@Test
public void string2Obj() throws Exception {
String str = "{\"name\":\"name\",\"age\":10,\"profileImageUrl\":\"link\"}";
Student student = JsonUtil.string2Obj(str, Student.class);
// Student(name=name, age=10, profileImageUrl=link)
System.out.println(student);
}
Various complex types of conversion, example 1:
public void string2Obj1() throws Exception {
Student student1 = new Student();
student1.setAge(10);
student1.setName("name1");
student1.setProfileImageUrl("link1");
Student student2 = new Student();
student2.setAge(20);
student2.setName("name2");
student2.setProfileImageUrl("link2");
List<Student> studentList = new ArrayList<>();
studentList.add(student1);
studentList.add(student2);
String result = JsonUtil.obj2String(studentList);
// [{"name":"name1","age":10,"profileImageUrl":"link1"},{"name":"name2","age":20,"profileImageUrl":"link2"}]
System.out.println(result);
List<Student> finalList = JsonUtil.string2Obj(result, List.class);
// [{name=name1, age=10, profileImageUrl=link1}, {name=name2, age=20, profileImageUrl=link2}]
System.out.println(finalList);
}
Conversion of complex types, example 2:
public void string2Obj2() throws Exception {
Map<String, List<Integer>> testMap = new HashMap<>();
testMap.put("1", Arrays.asList(1, 2, 3));
testMap.put("2", Arrays.asList(2, 3, 4));
String result = JsonUtil.obj2String(testMap);
// {"1":[1,2,3],"2":[2,3,4]}
System.out.println(result);
Map<String, List<Integer>> finalMap = JsonUtil.string2Obj(result, Map.class);
// {1=[1, 2, 3], 2=[2, 3, 4]}
System.out.println(finalMap);
}
You can use these 3 functions for serialization and deserialization operations
/** 将对象转为json */
public static <T> String obj2String(T obj)
/** 将对象转为json,并格式化显示 */
public static <T> String obj2StringPretty(T obj)
/** 将json转为对象 */
public static <T> T string2Obj(String str, Class<T> clazz)
The above three functions can fully meet your needs, here is a demonstration:
public void string2Obj3() throws Exception {
Student student1 = new Student();
student1.setAge(10);
student1.setName("name1");
student1.setProfileImageUrl("link1");
Student student2 = new Student();
student2.setAge(20);
student2.setName("name2");
student2.setProfileImageUrl("link2");
List<Student> studentList = new ArrayList<>();
studentList.add(student1);
studentList.add(student2);
String result = JsonUtil.obj2String(studentList);
// [{"name":"name1","age":10,"profileImageUrl":"link1"},{"name":"name2","age":20,"profileImageUrl":"link2"}]
System.out.println(result);
List<Student> finalList = JsonUtil.string2Obj(result, new TypeReference<List<Student>>() {
});
// [{name=name1, age=10, profileImageUrl=link1}, {name=name2, age=20, profileImageUrl=link2}]
System.out.println(finalList);
}
public void string2Obj4() throws Exception {
Student student1 = new Student();
student1.setAge(10);
student1.setName("name1");
student1.setProfileImageUrl("link1");
Student student2 = new Student();
student2.setAge(20);
student2.setName("name2");
student2.setProfileImageUrl("link2");
List<Student> studentList = new ArrayList<>();
studentList.add(student1);
studentList.add(student2);
String result = JsonUtil.obj2String(studentList);
// [{"name":"name1","age":10,"profileImageUrl":"link1"},{"name":"name2","age":20,"profileImageUrl":"link2"}]
System.out.println(result);
List<Student> finalList = JsonUtil.string2Obj(result, List.class, Student.class);
// [{name=name1, age=10, profileImageUrl=link1}, {name=name2, age=20, profileImageUrl=link2}]
System.out.println(finalList);
}