new Thread(() -> {
StringBuilder xml = new StringBuilder();
xml.append("<xml>");
xml.append("<appid>wx2421b1c4370ec43b</appid>");
xml.append("<mch_id>1608780863</mch_id>");
xml.append("<sub_appid>wx8888888888888888</sub_appid>");
xml.append("<sub_mch_id>10000101</sub_mch_id>");
xml.append("<nonce_str>mXTv7sDS6tjJAeXc</nonce_str>");
xml.append("<transaction_id>1008450740201411110005820873</transaction_id>");
xml.append("<sign>1C73F5844003D7F24A3F8A994DC32E2B</sign>");
xml.append("</xml>");
try {
byte[] xmlbyte = xml.toString().getBytes("UTF-8");
System.out.println(xml);
URL url = new URL("https://api.mch.weixin.qq.com/pay/orderquery");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setDoOutput(true);// 允许输出
conn.setDoInput(true);
conn.setUseCaches(false);// 不使用缓存
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");// 维持长连接
conn.setRequestProperty("Charset", "UTF-8");
conn.setRequestProperty("Content-Length",
String.valueOf(xmlbyte.length));
conn.setRequestProperty("Content-Type", "text/xml; charset=UTF-8");
conn.setRequestProperty("X-ClientType", "2");//发送自定义的头信息
conn.getOutputStream().write(xmlbyte);
conn.getOutputStream().flush();
conn.getOutputStream().close();
if (conn.getResponseCode() != 200)
throw new RuntimeException("请求url失败");
InputStream inputStream = conn.getInputStream();// 获取返回数据
// 使用输出流来输出字符(可选)
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int len;
while ((len = inputStream.read(buf)) != -1) {
out.write(buf, 0, len);
}
String string = out.toString("UTF-8");
System.out.println("输出字符:" + string);
out.close();
// xml pull解析
XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); // 创建一个xml解析的工厂
XmlPullParser parser = factory.newPullParser(); // 获得xml解析类的引用
parser.setInput(new StringReader(string));
int eventType = parser.getEventType(); // 获得事件的类型
while (eventType != XmlPullParser.END_DOCUMENT) {
switch (eventType) {
case XmlPullParser.START_DOCUMENT:
System.out.println("------------------开始------------------");
break;
case XmlPullParser.START_TAG:
String parserName = parser.getName();
if (parserName.equals("return_code")){
System.out.println("return_code"+parser.nextText());
}
else if (parserName.equals("return_msg")){
System.out.println("return_msg"+parser.nextText());
}
break;
case XmlPullParser.END_TAG:
System.out.println("------------------结束------------------");
break;
}
eventType = parser.next();
}
} catch (UnsupportedEncodingException | MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
}
}).start();
Android xml 文件格式 请求
最新推荐文章于 2023-12-11 11:30:48 发布