Java示例

下面的代码调用获取区域项目计数检索所有地区和国家及其相关项目计数的API操作。

代码示例使用了Jakarta Commons HttpClient可以下载的库在这里

示例请求

进口java.io.ByteArrayOutputStream;进口java.io.IOException;进口org.apache.commons.httpclient.HttpClient;进口org.apache.commons.httpclient.methods.GetMethod;公共类SampleApiCall{/** *测试工具。*/ public static void main(String[] args) {String host = "https://api.globalgiving.org";String操作= "/api/public/projectservice/regions/ nations /projects/count";String api_key = "YOUR_API_KEY";字符串url = host + operation + "?Api_key =" + Api_key;try{字符串响应= getResponse(url); System.out.println(response); } catch (IOException e) { e.printStackTrace(); } } /* * Retrieve response using commons HttpClient API. */ private static String getResponse(String url) throws IOException { GetMethod get = new GetMethod(url); new HttpClient().executeMethod(get); ByteArrayOutputStream outputStream = new ByteArrayOutputStream() ; byte[] byteArray = new byte[1024]; int count = 0 ; while((count = get.getResponseBodyAsStream().read(byteArray, 0, byteArray.length)) > 0) { outputStream.write(byteArray, 0, count) ; } return new String(outputStream.toByteArray(), "UTF-8"); } }

示例响应

<?XML版本="1.0" encoding="utf-8" standalone="yes"?>     BW博茨瓦纳 1   BF 布基纳法索   BI   布隆迪 1   CM喀麦隆 7  CD 刚果,民主共和国    CI  C™te d' ivory  1   EG 埃及 1   ET埃塞俄比亚 6   GM冈比亚,The 1   GH Ghana 23   GW  几内亚比绍  Guinea-Bissau  KE   肯尼亚 70   LR4 < projectCount > < / projectCount > < /国家> <中国> < iso3166CountryCode > MG < / iso3166CountryCode > <名称>马达加斯加< /名称> < projectCount > 3 < / projectCount > < /国家> <中国> < iso3166CountryCode > MW < / iso3166CountryCode > <名称>马拉维< /名称> < projectCount > 5 < / projectCount > < /国家> <中国> < iso3166CountryCode >毫升< / iso3166CountryCode > <名称>马里< /名称> < projectCount > 6 < / projectCount > < /国家> <中国> < iso3166CountryCode >马< / iso3166CountryCode > <名称>摩洛哥< /名称> < projectCount > 2 < / projectCount >  MZ 莫桑比克 3   NA    NE    Niger  Niger   NG 尼日利亚 10  RW卢旺达 20   SN Senegal  Senegal  SL   SL Sierra Leone    SO 索马里 2  ZA South Africa 20   SD Sudan 13   TZ Tanzania, United Republic of 12   TG Togo 3   UG Uganda 40   ZM Zambia 2   ZW Zimbabwe 8   Africa   . . .  
警告:Javascript目前被禁用或在您的浏览器中不可用。GlobalGiving大量使用Javascript,禁用Javascript将无法正常工作。请启用Javascript并刷新此页面。
Baidu
map