Hutool 参考文档
<dependency>
<groupId>cn.hutoolgroupId>
<artifactId>hutool-allartifactId>
<version>4.1.2version>
dependency>
HttpUtil.get(url,paramMap,timeOut);
HttpUtil.post(同上)
//=====
String url = "https://xxx/xx";//指定URL
Map<String, Object> map = new HashMap<>();//存放参数
map.put("A", 100);
map.put("B", 200);
HashMap<String, String> headers = new HashMap<>();//存放请求头,可以存放多个请求头
headers.put("xxx", xxx);
//发送get请求并接收响应数据
String result= HttpUtil.createGet(url).addHeaders(headers).form(map).execute().body();
//发送post请求并接收响应数据
String result= HttpUtil.createPost(url).addHeaders(headers).form(map).execute().body();
String url = "https://xxx/delete/"+id;//指定URL携带ID
HashMap<String, String> headers = new HashMap<>();//存放请求头,可以存放多个请求头
headers.put("xxx", xxx);
//发送delete请求并接收响应数据
String result= HttpUtil.createRequest(Method.DELETE, url).addHeaders(headers).execute().body();
@Test
public void testHttps() throws Exception {
JSONObject json = new JSONObject();
json.put("username", "1332788xxxxxx");
json.put("password", "123456.");
String result = HttpRequest.post("https://api2.bmob.cn/1/users")
.header("Content-Type", "application/json")//头信息,多个头信息多次调用此方法即可
.header("X-Bmob-Application-Id","2f0419a31f9casdfdsf431f6cd297fdd3e28fds4af")
.header("X-Bmob-REST-API-Key","1e03efdas82178723afdsafsda4be0f305def6708cc6")
.body(json)
.execute().body();
System.out.println(result);
}
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>1.2.70version>
dependency>
转换成json字符串
List<User> userList = new ArrayList<>();
User user = new User();
user.setName("123");
userList.add(user);
//实体类转换json
JSON.toJSONString(user)
//list转换json
JSON.toJSONString(userList)
转换成对象
public class Json {
public static void main(String[] args) {
//实体
String json = "{\"age\":20,\"name\":\"name0\"}";
JSON.parseObject(json, User.class);
//list集合
String json = "[{\"age\":20,\"name\":\"name0\"}]";
List<User> userList = JSON.parseArray(json, User.class);
}
}
json转换jsonobj直接获取属性
//定义一个json格式的字符串
String message = "{"code":1,"data":{"id":1001,"name":"lisi"}}";
//将字符串转换成json
JSONObject jsonObject = JSONObject.parseObject(message);
//取出data里的数据
String code = jsonObject.getString("code");
String data = jsonObject.getString("data");
System.out.println(code); //输出结果为:1
System.out.println(data); //输出结果为:{"name":"lisi","id":1001}
转换成指定的集合
List<Map<String, Object>> res = JSONObject.parseObject("xxxxjson", new TypeReference<List<Map<String, Object>>>() {});
百度吧 其实跟fastjson用法差别不大