后台post发送XML

来源:互联网 发布:德哈维兰 知乎 编辑:程序博客网 时间:2024/05/29 12:30

后台post发送XML


这里使用了微信平台模拟请-


import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.io.OutputStreamWriter;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;public class HttpClientAndXml {/** * @param args * @throws Exception  */public static void main(String[] args) throws Exception {// TODO Auto-generated method stubString remoteUrl="https://api.mch.weixin.qq.com/pay/unifiedorder";String xmlStr="<xml>"+"<appid>1</appid>"+"<mch_id>1</mch_id>"+"<nonce_str>1</nonce_str>"+"<sign><![CDATA[1]]></sign>"+"<body><![CDATA[1]]></body>"+"<attach><![CDATA[1]]></attach>"+"<out_trade_no>1</out_trade_no>"+"<total_fee>1</total_fee>"+"<spbill_create_ip>1</spbill_create_ip>"+"<notify_url>1</notify_url>"+"<trade_type>1</trade_type>"+"<openid>1</openid>"+"</xml>";String encoding="utf-8";HttpClientAndXml hcax=new HttpClientAndXml();String relStr=hcax.sendXML(remoteUrl, xmlStr, encoding);System.out.println(relStr);}/** * post向某地址发送xml报文 *  * @param remoteUrl  发送的地址 * @param reqStr    发送的xml报文 * @param encoding   发送的字符编码格式-一般写utf-8 * @return * @throws Exception */public String sendXML(String remoteUrl, String xmlStr, String encoding) throws Exception{String strResponse = "";      String strMessage = "";      InputStream inputStream;      OutputStream outputStream;      OutputStreamWriter writer;      URL url;      HttpURLConnection connection;      try {          url = new URL(remoteUrl);          connection = (HttpURLConnection) url.openConnection();          connection.setDoInput(true);          connection.setDoOutput(true);          connection.setRequestMethod("POST");          connection.setAllowUserInteraction(true);          //设置超时          String strTimeOut = "6000";          if (strTimeOut != null) {              connection.setConnectTimeout(Integer.parseInt(strTimeOut));              connection.setReadTimeout(Integer.parseInt(strTimeOut));          }          connection.connect();          outputStream = connection.getOutputStream();          writer = new OutputStreamWriter(outputStream, encoding);          writer.write(xmlStr);          writer.flush();          writer.close();          inputStream = connection.getInputStream();          int status = connection.getResponseCode();          if (status == 200) {              BufferedReader reader;              reader = new BufferedReader(new InputStreamReader(inputStream, encoding));              while ((strMessage = reader.readLine()) != null) {                  strResponse += strMessage;              }              reader.close();          } else {              strResponse = "error";          }          inputStream.close();      } catch (MalformedURLException e) {      } catch (IOException e) {      } catch (Exception e) {      }    return strResponse;   }}


0 0
原创粉丝点击