簡體   English   中英

HTTP從API獲取對XML的請求

[英]HTTP Get request for XML from API

我對使用Java調用API來請求XML的API特別陌生,因此我使用的是模板。 可以在下面看到。

但是,既然我要從另一個Web API調用API,則它們要求我使用我一無所知的python或使用第三方HTTP Web client 相反,我希望對API的調用在我的Java應用程序內部。 是否可以使用以下標頭更改以下代碼?

樣本請求URL:http:// datamall.mytransport.sg/ltaodataservice.svc/TravelTimeSet

請求標頭:AccountKey = xxx,UniqueUserId = xxx,accept = application / atom + xml

API文檔/指南

NowCast.java * NowCast.java鏈接到SAX解析器

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class NowCast extends SAXParser {

public static void main(String[] args) {

    String datasetName, keyRef;
    datasetName = "Nowcast";
    keyRef = "781CF461BB6606ADEA6B1B4F3228DE9DB26ABF1B1B755E93";

    NowCast od = new NowCast();

    try {
        od.callWebAPI(datasetName, keyRef);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

private void callWebAPI(String datasetName, String keyRef) throws Exception {
    // Step 1: Construct URL
    String url = "http://www.nea.gov.sg/api/WebAPI?dataset=" + datasetName
            + "&keyref=" + keyRef;

    // Step 2: Call API Url
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    con.setRequestMethod("GET");
    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'GET' request to URL : " + url);
    System.out.println("Response Code : " + responseCode);
    // Step 3: Check the response status
    if (responseCode == 200) {
        // Step 3a: If response status == 200
        // print the received xml
        super.Parserr(con.getInputStream());
        System.out.println(readStream(con.getInputStream()));
    } else {
        // Step 3b: If response status != 200
        // print the error received from server
        System.out.println("Error in accessing API - "
                + readStream(con.getErrorStream()));
    }
}

// Read the responded result
private String readStream(InputStream inputStream) throws Exception {
    BufferedReader reader = new BufferedReader(new InputStreamReader(
            inputStream));
    String inputLine;
    StringBuffer response = new StringBuffer();
    while ((inputLine = reader.readLine()) != null) {
        response.append(inputLine);
    }
    reader.close();
    return response.toString();
}

}

我將python代碼(在API文檔中)與上面的代碼交叉引用,並解決了問題

在Java中設置請求標頭

URL obj =新的URL(URL);

HttpURLConnection con =(HttpURLConnection)obj.openConnection();

con.setRequestMethod( “GET”);

con.setRequestProperty(“ AccountKey”,“ zIIkxPOqBRxnkH97G6ZGlA ==”);;

con.setRequestProperty(“ UniqueUserID”,“ 5ccef4a0-10e2-4f75-8f4d-2be67885b10f”);

con.setRequestProperty(“ accept”,“ application / atom + xml”);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM