標籤:while print content 地址 ebs 資料格式 output todo connect
最近對接了個webService的介面取資料,從網上良莠不齊的代碼中找到了個方法, 具體作者已經記不住是誰了,現在把代碼貼出來,希望可以幫到大家,代碼如下,簡單粗暴
public String getWebService(){ HttpURLConnection connection = null; OutputStream os = null; int responseCode = 0; StringBuilder sb = new StringBuilder(); //第一步:建立服務地址,不是WSDL地址 URL url = null; try { url = new URL(""); //*****這裡填寫url地址 } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } //第二步:開啟一個通向服務地址的串連 try { connection = (HttpURLConnection) url.openConnection(); //第三步:設定參數 //3.1發送方式設定:POST必須大寫 connection.setRequestMethod("POST"); //3.2設定資料格式:content-type connection.setRequestProperty("content-type", "text/xml;charset=utf-8"); //3.3設定輸入輸出,因為預設新建立的connection沒有讀寫權限, connection.setDoInput(true); connection.setDoOutput(true); os = connection.getOutputStream(); //第五步:接收服務端響應,列印 responseCode = connection.getResponseCode(); String temp = null; if(200 == responseCode){//表示服務端響應成功 InputStream is = connection.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); while(null != (temp = br.readLine())){ sb.append(temp); } System.out.println(sb.toString()); is.close(); isr.close(); br.close(); } os.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return sb.toString(); }
Java 請求webServce介面