Java如何通過URL調用遠程接口並讀取返回信息?

String ticket = "";//登錄憑證
        String url_str = "http://www.sina.com.cn?ticket=";//獲取用戶認證的帳號URL
        String ticket_url = url_str + ticket;
        URL url = new URL(ticket_url);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.connect();

        int code = connection.getResponseCode();
        if (code == 404) {
            throw new Exception("認證無效,找不到此次認證的會話信息!");
        }
        if (code == 500) {
            throw new Exception("認證服務器發生內部錯誤!");
        }
        if (code != 200) {
            throw new Exception("發生其它錯誤,認證服務器返回 " + code);
        }
        InputStream is = connection.getInputStream();
        byte[] response = new byte[is.available()];
        is.read(response);
        is.close();
        if (response == null || response.length == 0) {
            throw new Exception("認證無效,找不到此次認證的會話信息!");
        }
        String userId = new String(response, "GBK");
        System.out.println(userId);

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章