JAVA如何调用对方http接口得到返回数据

来源:互联网 发布:勇士雷霆g5数据 编辑:程序博客网 时间:2024/05/20 23:33

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;}}



原创粉丝点击