java读取json文件为list,并进行rest传输(单纯的为自己记录代码,免得要用的时候找不到)
读取json文件(两个方法)
- 从工程里读取json文件
String dir = request.getSession().getServletContext().getRealPath("/resource/文件名.json");
- 从本地读取json文件
String dir = "C:\\Users\\Desktop\\文件名.json";
文件处理成List(借助com.alibaba.fastjson.JSONObject)
fastjson 版本用的是1.2.20 低版本有些情况会报错(具体哪一版修复的不太清楚)
List<Map<String,Object>> maps = new ArrayList<>();
try {
//转换为文件
File file = new File(dir);
if (!file.exists()) {
file.createNewFile();
}
//把读入的文件转换为字符,以便json去处理
String str= FileUtils.readFileToString(file, "UTF-8");
//借助阿里的fastJson处理
maps = (List)JSONObject.parseArray(str,Map.class);
} catch (Exception e) {
e.printStackTrace();
}
起线程池发起rest请求
起线程池:
ThreadPoolExecutor executor = new ThreadPoolExecutor(5, 10, 200, TimeUnit.MILLISECONDS,
new ArrayBlockingQueue<Runnable>(5));
发送请求:
省略for循环遍历maps的过程
final String mapStr = JSONObject.toJSONString(maps.get(i));
executor.execute(new Runnable() {
@Override
public void run() {
HttpClient httpClient = new HttpClient();
PostMethod method = new PostMethod("rest访问地址");
try{
RequestEntity requestEntity = new StringRequestEntity(mapStr, "application/json", "utf-8");
method.setRequestEntity(requestEntity);
//状态返回码
int statusCode = httpClient.executeMethod(method);
//下面是捕获返回的response值
if (statusCode == 200) {
StringBuilder sb = new StringBuilder();
InputStream ins = method.getResponseBodyAsStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(ins,"UTF-8"));
String line = " ";
while ((line = reader.readLine()) != null){
sb.append(line);
}
System.out.println(sb.toString());
//或者用字节读
//InputStream ins = null;
//StringBuilder sb = new StringBuilder();
//ins = method.getResponseBodyAsStream();
//byte[] b = new byte[1024];
//int r_len = 0;
//while ((r_len = ins.read(b)) > 0) {
// sb.append(new String(b, 0, r_len, method.getResponseCharSet()));
//}
//System.out.println(sb.toString());
}
}catch (Exception e){
System.out.println("212121");
e.printStackTrace();
}
}
});
json例子
[{"id":11,"jsonrpc":"2.0","params":{"id":1}},
{"id":22,"jsonrpc":"2.0","params":{"id":2}},
{"id":33,"jsonrpc":"2.0","params":{"id":3}},
{"id":44,"jsonrpc":"2.0","params":{"id":4}}]