简体   繁体   English

使用 java.net.URL 发送 API 密钥

[英]Sending API key using java.net.URL

I am trying to send an API key to access some data.我正在尝试发送一个 API 密钥来访问一些数据。 This data needs to be returned as an input stream, so I can parse through it.这个数据需要作为输入流返回,所以我可以解析它。 I am using java.net.URL to access the site, but I can't find a way to send an API key with my http request.我正在使用java.net.URL访问该站点,但找不到通过 http 请求发送 API 密钥的方法。

URL url = new URL("My specified URL for the API");

        FeedMessage feed = FeedMessage.parseFrom(url.openStream());
        for (FeedEntity entity : feed.getEntityList()) {
            if (entity.hasTripUpdate()) {
                System.out.println(entity.getTripUpdate());
            }
        }

I ended up using these libraries to solve this problem:我最终使用这些库来解决这个问题:

import java.io.InputStream;
import com.google.transit.realtime.GtfsRealtime.FeedEntity;
import com.google.transit.realtime.GtfsRealtime.FeedMessage;

import java.net.URI;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

This allowed me to get the data I wanted from the API and then convert it into an input stream.这使我能够从 API 获取我想要的数据,然后将其转换为输入流。 The code that allowed me to do that is below.允许我这样做的代码如下。

HttpClient httpclient = HttpClients.createDefault();
        try
        {
            URIBuilder builder = new URIBuilder("URL");

            URI uri = builder.build();
            HttpGet request = new HttpGet(uri);
            request.setHeader("Cache-Control", "no-cache");
            request.setHeader("Ocp-Apim-Subscription-Key", "API-Key");


            HttpResponse response = httpclient.execute(request);
            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();

            FeedMessage feed = FeedMessage.parseFrom(content);
         }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM