最近對接了個webService的接口取數據,從網上參差不齊的代碼中找到了個方法, 具體做者已經記不住是誰了,如今把代碼貼出來,但願能夠幫到你們,代碼以下,簡單粗暴web
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(); }