import com.alibaba.fastjson.JSON;
import com.api.zp.documentexchange.OkHttp;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.dom4j.*;
import org.xml.sax.SAXException;
import selfdev.util.log.LogTool;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.*;
import java.nio.charset.Charset;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class ZipTest {
public static String requestUrlGetStrXml(String dnFileUrl) throws IOException {
dnFileUrl = dnFileUrl.replace("", "");
LOGGER.writeLog("dnFileUrl: "+dnFileUrl);
ZipInputStream zipInputStream = null;
BufferedReader br = null;
// URL url = new URL(dnFileUrl);
// HttpURLConnection conn = (HttpURLConnection)url.openConnection();
Charset utf8 = Charset.forName("utf-8");
// int resultCode = conn.getResponseCode();
StringBuilder sb=new StringBuilder();
//OKhttp访问
OkHttpClient okClient = OkHttp.getUnsafeOkHttpClient();
Request request =new Request.Builder()
.url(dnFileUrl)
.build();
Response response = okClient.newCall(request).execute();
InputStream inputStream = response.body().byteStream();
BufferedInputStream in = new BufferedInputStream(inputStream,4096);
zipInputStream = new ZipInputStream(in);
ZipEntry zipEntry;
LOGGER.writeLog("Charset.defaultCharset() "+Charset.defaultCharset());
while ((zipEntry = zipInputStream.getNextEntry()) != null) {
if (zipEntry.toString().endsWith(".xml")) {
//设置原本 xml 的编码 ps:如果和原来的xml编码不一致就会出现乱码
br = new BufferedReader(new InputStreamReader(zipInputStream,utf8));
String line;
while ((line = br.readLine()) != null) {
LOGGER.writeLog(line);
// String gbk = new String(line.getBytes("gbk"),
// "utf-8");
// String gbkk = new String(line.getBytes(utf8));
// LOGGER.writeLog(gbkk);
sb.append(line);
}
}
}
return sb.toString();
}
//解析xml
public static Map parseXml(String strXml) throws DocumentException {
Map<String,String> map=new HashMap<>();
Document document = DocumentHelper.parseText(strXml);
Element root = document.getRootElement();
Element object = root.element("OBJECT");
List item = object.elements("ITEM");
for (Iterator<?> it = item.iterator(); it.hasNext();) {
Element e = (Element) it.next();
String value = e.attributeValue("NAME");
if (value.equals("DOC_FILE")) {
Element row = e.element("ROW");
List item1 = row.elements();
Iterator iterator = item1.iterator();
while (iterator.hasNext()) {
Element next = (Element) iterator.next();
String name = next.attributeValue("NAME");
String text = next.getText();
map.put(name,text);
}
}
}
return map;
}
}
通过超链接 解析zip压缩包 中的 xml 内容
于 2021-09-16 14:19:40 首次发布