package ljj;
import ljj.entity.Customer;
import ljj.mapper.CustomerMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.Assert;
import java.io.IOException;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SampleTest {
@Autowired
private CustomerMapper customerMapper;
@Test
public void testSelect() {
System.out.println(("----- selectAll method test ------"));
List<Customer> customers = customerMapper.selectList(null);
Assert.notEmpty(customers);
// Assert.assertEquals(5, customers.size());
customers.forEach(System.out::println);
}
}
可以把的到的json转换成java对象
ObjectMapper jsonMapper = new ObjectMapper();
@Test
public void testHttp() throws IOException {
HttpClient httpClient = HttpClients.createDefault();
HttpResponse response = httpClient.execute(new HttpGet("https://www.baidu.com"));
Assert.notNull(response);
System.out.println(response);
}
spring提供的简单方法.
@Test
public void testHttp() throws IOException {
RestTemplate rest = new RestTemplate();
rest.getForObject("",Float.class);
}
post
package com.yh;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.SneakyThrows;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.junit.Test;
import tk.mybatis.mapper.util.Assert;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.nio.charset.StandardCharsets;
public class insertData2DB {
@SneakyThrows
@Test
public void insert() {
CloseableHttpClient client = HttpClients.createDefault();
URI uri = new URI("http", null, "localhost", 8081, "/report/account", "currentPage=1&pageSize=15&depotId=&monthTime=2019-11", null);
HttpPost post = new HttpPost(uri);
CloseableHttpResponse response = client.execute(post);
Assert.notNull(response, "请求失败");
JSONObject json = getJsonFromInputStream(response.getEntity().getContent());
System.out.println(json);
System.out.println(json.getJSONObject("data").getJSONArray("rows").getJSONObject(0).getString("materialName"));
}
public JSONObject getJsonFromInputStream(InputStream inputStream) {
StringBuilder sBuilder = new StringBuilder();
byte[] buff = new byte[256];
int read = 0;
do {
sBuilder.append(new String(buff, 0, read, StandardCharsets.UTF_8));
try {
read = inputStream.read(buff);
} catch (IOException e) {
e.printStackTrace();
}
} while (read > 0);
return JSON.parseObject(sBuilder.toString());
}
}
评论区