對於java用發送http請求,請求內容為xml格式

來源:互聯網
上載者:User
package com.infowarelab.test;import java.io.BufferedInputStream;import java.io.BufferedReader;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStreamWriter;import java.net.URI;import java.net.URL;import java.net.URLConnection;import org.apache.commons.httpclient.HttpClient;import org.apache.commons.httpclient.HttpStatus;import org.apache.commons.httpclient.methods.PostMethod;/** * 測試調用一些meeting第三方介面 * @author Jack.Song */public class TestMeetingInterface {/** * @param args */public static void main(String[] args) {String url = "http://192.168.0.68/integration/xml";TestMeetingInterface tmi = new TestMeetingInterface();System.out.println(tmi.post(url,"listSummaryMeeting.xml"));/*//判斷當前系統是否支援Java AWT Desktop擴充        if(java.awt.Desktop.isDesktopSupported()){            try {            URI path = tmi.getClass().getResource("/listSummaryMeeting.xml").toURI();            System.out.println(path);                //建立一個URI執行個體//              java.net.URI uri = java.net.URI.create(path);                 //擷取當前系統案頭擴充                java.awt.Desktop dp = java.awt.Desktop.getDesktop();                //判斷系統案頭是否支援要執行的功能                if(dp.isSupported(java.awt.Desktop.Action.BROWSE)){                    //擷取系統預設瀏覽器開啟連結                    dp.browse(path);                    }            } catch (Exception e) {                e.printStackTrace();            }                     }*/}    /**      * 發送xml資料請求到server端      * @param url xml請求資料地址      * @param xmlString 發送的xml資料流      * @return null發送失敗,否則返迴響應內容      */      public String post(String url,String xmlFileName){          //關閉        System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog");           System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true");           System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient", "stdout");                  //建立httpclient工具對象        HttpClient client = new HttpClient();          //建立post要求方法        PostMethod myPost = new PostMethod(url);          //佈建要求逾時時間        client.setConnectionTimeout(300*1000);        String responseString = null;          try{          //佈建要求頭部類型        myPost.setRequestHeader("Content-Type","text/xml");        myPost.setRequestHeader("charset","utf-8");                //佈建要求體,即xml常值內容,註:這裡寫了兩種方式,一種是直接擷取xml內容字串,一種是讀取xml檔案以流的形式//        myPost.setRequestBody(xmlString);                InputStream body=this.getClass().getResourceAsStream("/"+xmlFileName);        myPost.setRequestBody(body);//            myPost.setRequestEntity(new StringRequestEntity(xmlString,"text/xml","utf-8"));              int statusCode = client.executeMethod(myPost);              if(statusCode == HttpStatus.SC_OK){                  BufferedInputStream bis = new BufferedInputStream(myPost.getResponseBodyAsStream());                  byte[] bytes = new byte[1024];                  ByteArrayOutputStream bos = new ByteArrayOutputStream();                  int count = 0;                  while((count = bis.read(bytes))!= -1){                      bos.write(bytes, 0, count);                  }                  byte[] strByte = bos.toByteArray();                  responseString = new String(strByte,0,strByte.length,"utf-8");                  bos.close();                  bis.close();              }          }catch (Exception e) {              e.printStackTrace();          }          myPost.releaseConnection();          return responseString;      }          /** * 用傳統的URI類進行請求 * @param urlStr */public void testPost(String urlStr) {        try {            URL url = new URL(urlStr);            URLConnection con = url.openConnection();            con.setDoOutput(true);            con.setRequestProperty("Pragma:", "no-cache");            con.setRequestProperty("Cache-Control", "no-cache");            con.setRequestProperty("Content-Type", "text/xml");            OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());                String xmlInfo = getXmlInfo();            System.out.println("urlStr=" + urlStr);//            System.out.println("xmlInfo=" + xmlInfo);            out.write(new String(xmlInfo.getBytes("UTF-8")));            out.flush();            out.close();            BufferedReader br = new BufferedReader(new InputStreamReader(con                    .getInputStream()));            String line = "";            for (line = br.readLine(); line != null; line = br.readLine()) {                System.out.println(line);            }        } catch (Exception e) {            e.printStackTrace();        }    }    private String getXmlInfo() {        StringBuilder sb = new StringBuilder();        sb.append("<?xml version='1.0' encoding='UTF-8'?>");        sb.append("<Message>");        sb.append("<header>");        sb.append("<action>readMeetingStatus</action>");        sb.append("<service>meeting</service>");        sb.append("<type>xml</type>");        sb.append("<userName>admin</userName>");        sb.append("<password>admin</password>");        sb.append("<siteName>box</siteName>");        sb.append("</header>");        sb.append("<body>");        sb.append("<confKey>43283344</confKey>");        sb.append("</body>");        sb.append("</Message>");                return sb.toString();    }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.