最近对接了个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(); }