JAVA如何呼叫對方http介面得到返回資料
阿新 • • 發佈:2019-02-18
http://www.anjismart.com:7770/QueryCodeService.asmx/QueryCode?code=425144174493800&aid=302
瀏覽器訪問該連結的資料:
<?xml version="1.0" encoding="UTF-8"?>
<string xmlns="http://www.anjismart.com/">j</string>
通過JAVA程式碼如何訪問:
package com.accord.test; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class Test { public static void main(String[] args) throws Exception { //方法一 //System.out.println((new Test()).getURLContent()); String urlStr = "http://www.anjismart.com:7770/QueryCodeService.asmx/QueryCode?code=425144174493800&aid=302"; System.out.println((new Test()).getURLContent(urlStr)); } public static String getURLContent() throws Exception { String strURL = "http://www.anjismart.com:7770/QueryCodeService.asmx/QueryCode?code=425144174493800&aid=302"; URL url = new URL(strURL); HttpURLConnection httpConn = (HttpURLConnection)url.openConnection(); httpConn.setRequestMethod("GET"); httpConn.connect(); BufferedReader reader = new BufferedReader(new InputStreamReader(httpConn.getInputStream())); String line; StringBuffer buffer = new StringBuffer(); while ((line = reader.readLine()) != null) { buffer.append(line); } reader.close(); httpConn.disconnect(); System.out.println(buffer.toString()); return buffer.toString(); } /** * 程式中訪問http資料介面 */ public static String getURLContent(String urlStr) { /** 網路的url地址 */ URL url = null; /** http連線 */ HttpURLConnection httpConn = null; /**//** 輸入流 */ BufferedReader in = null; StringBuffer sb = new StringBuffer(); try { url = new URL(urlStr); in = new BufferedReader(new InputStreamReader(url.openStream(), "GBK")); String str = null; while ((str = in.readLine()) != null) { sb.append(str); } } catch (Exception ex) { } finally { try { if (in != null) { in.close(); } } catch (IOException ex) { } } String result = sb.toString(); System.out.println(result); return result; } }