java 請求第三方接口 GET\POST 實現方法


(1)GET方法

    /**
     * 根據高德地圖api獲取位置信息
     * @return
     * 
     */
    public static String getMapAddInfo(String httpurl) {
        HttpURLConnection connection = null;
        InputStream is = null;
        BufferedReader br = null;
        String result = null;// 返回結果字符串
        try {
            // 創建遠程url連接對象
            URL url = new URL("http://restapi.amap.com/v3/geocode/geo?address=陝西西安 
            &output=XML&key=b6acf6e6c98f32be96e757ede9a9aee3");
            // 通過遠程url連接對象打開一個連接,強轉成httpURLConnection類
            connection = (HttpURLConnection) url.openConnection();
            // 設置連接方式:get
            connection.setRequestMethod("GET");
            // 設置連接主機服務器的超時時間:15000毫秒
            connection.setConnectTimeout(15000);
            // 設置讀取遠程返回的數據時間:60000毫秒
            connection.setReadTimeout(60000);
            // 發送請求
            connection.connect();
            // 通過connection連接,獲取輸入流
            if (connection.getResponseCode() == 200) {
                is = connection.getInputStream();
                // 封裝輸入流is,並指定字符集
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                // 存放數據
                StringBuffer sbf = new StringBuffer();
                String temp = null;
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append("\r\n");
                }
                result = sbf.toString();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 關閉資源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            connection.disconnect();// 關閉遠程連接
        }
        System.out.println(result);
        return result;
    }

返回的xml格式化后:

<?xml version="1.0" encoding="UTF-8"?>
<response>
    <status>1</status>
    <info>OK</info>
    <infocode>10000</infocode>
    <count>1</count>
    <geocodes type="list">
        <geocode>
            <formatted_address>陝西省西安市</formatted_address>
            <country>中國</country>
            <province>陝西省</province>
            <citycode>029</citycode>
            <city>西安市</city>
            <district></district>
            <township></township>
            <neighborhood>
                <name></name>
                <type></type>
            </neighborhood>
            <building>
                <name></name>
                <type></type>
            </building>
            <adcode>610100</adcode>
            <street></street>
            <number></number>
            <location>108.940174,34.341568</location>
            <level>市</level>
        </geocode>
    </geocodes>
</response>

(2)POST方法

/**
     * 根據接口獲取信息
     * @return
     * @throws IOException
     */
public static String postMapAddInfo(String httpUrl, String param) {
        HttpURLConnection connection = null;
        InputStream is = null;
        OutputStream os = null;
        BufferedReader br = null;
        String result = null;
        try {
            URL url = new URL("http://localhost:8080/getAll");
            // 通過遠程url連接對象打開連接
            connection = (HttpURLConnection) url.openConnection();
            // 設置連接請求方式
            connection.setRequestMethod("POST");
            // 設置連接主機服務器超時時間:15000毫秒
            connection.setConnectTimeout(15000);
            // 設置讀取主機服務器返回數據超時時間:60000毫秒
            connection.setReadTimeout(60000);
            // 默認值為:false,當向遠程服務器傳送數據/寫數據時,需要設置為true
            connection.setDoOutput(true);
            // 默認值為:true,當前向遠程服務讀取數據時,設置為true,該參數可有可無
            connection.setDoInput(true);
            // 設置傳入參數的格式:請求參數應該是 name1=value1&name2=value2 的形式。
            connection.setRequestProperty("Content-Type", "application/json");
            // 通過連接對象獲取一個輸出流
            os = connection.getOutputStream();
            // 通過輸出流對象將參數寫出去/傳輸出去,它是通過字節數組寫出的
            os.write(param.getBytes());
            // 通過連接對象獲取一個輸入流,向遠程讀取
            if (connection.getResponseCode() == 200) {

                is = connection.getInputStream();
                // 對輸入流對象進行包裝:charset根據工作項目組的要求來設置
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

                StringBuffer sbf = new StringBuffer();
                String temp = null;
                // 循環遍歷一行一行讀取數據
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append("\r\n");
                }
                result = sbf.toString();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 關閉資源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            // 斷開與遠程地址url的連接
            connection.disconnect();
        }
        System.out.println(result);
        return result;
}

(3)POST方法 代碼實現方法傳form-data參數

注意:一定注意參數應是拼接傳入,例如:String str = "name = zxl&sex =男 "

/**
     * 當使用此方法 connection.getResponseCode() 方法報401時 ,請設置請求頭,如何請求頭有問題則報401 無法訪問
     * @param httpUrl
     * @param param
     * @return
     */
    public static String doPost(String httpUrl, String param) {

        HttpURLConnection connection = null;
        InputStream is = null;
        OutputStream os = null;
        BufferedReader br = null;
        String result = null;
        try {
            URL url = new URL(httpUrl);
            // 通過遠程url連接對象打開連接
            connection = (HttpURLConnection) url.openConnection();
            // 設置連接請求方式
            connection.setRequestMethod("POST");
            // 設置連接主機服務器超時時間:15000毫秒
            connection.setConnectTimeout(15000);
            // 設置讀取主機服務器返回數據超時時間:60000毫秒
            connection.setReadTimeout(60000);

            // 默認值為:false,當向遠程服務器傳送數據/寫數據時,需要設置為true
            connection.setDoOutput(true);
            // 默認值為:true,當前向遠程服務讀取數據時,設置為true,該參數可有可無
            connection.setDoInput(true);
            // 設置傳入參數的格式:請求參數應該是 name1=value1&name2=value2 的形式。
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            // 通過連接對象獲取一個輸出流
            os = connection.getOutputStream();
            // 通過輸出流對象將參數寫出去/傳輸出去,它是通過字節數組寫出的
            os.write(param.getBytes());
            // 通過連接對象獲取一個輸入流,向遠程讀取
            if (connection.getResponseCode() == 200) {

                is = connection.getInputStream();
                // 對輸入流對象進行包裝:charset根據工作項目組的要求來設置
                br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

                StringBuffer sbf = new StringBuffer();
                String temp = null;
                // 循環遍歷一行一行讀取數據
                while ((temp = br.readLine()) != null) {
                    sbf.append(temp);
                    sbf.append("\r\n");
                }
                result = sbf.toString();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 關閉資源
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            // 斷開與遠程地址url的連接
            connection.disconnect();
        }
        return result;
    }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM