HTTP get 요청의 헤더에 apikey가있는 x-api-key를 설정하려면 어떻게해야합니까? 나는 무언가를 시도했지만 그것이 작동하지 않는 것 같습니다. 다음은 내 코드입니다 :HTTP get 요청의 헤더에 X-Api-Key를 설정하는 방법
private static String download(String theUrl)
{
try {
URL url = new URL(theUrl);
URLConnection ucon = url.openConnection();
ucon.addRequestProperty("x-api-key", apiKey);
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current;
while ((current = bis.read()) != -1)
{
baf.append((byte) current);
}
return new String (baf.toByteArray());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
편집 : 는 아래의 대답은 여전히 오류 메시지가 표시와 함께 코드를 변경 :이 유형의 HttpURLConnection의 (URL)를 인스턴스화 할 수 있습니다. 나는 그것을 변경하지만 지금은 대신 URLConnection
를 사용
private static String download(String theUrl)
{
try {
URL url = new URL(theUrl);
URLConnection ucon = new HttpURLConnection(url) {
@Override
public void connect() throws IOException {
// TODO Auto-generated method stub
}
@Override
public boolean usingProxy() {
// TODO Auto-generated method stub
return false;
}
@Override
public void disconnect() {
// TODO Auto-generated method stub
}
};
ucon.addRequestProperty("x-api-key", apiKey);
ucon.connect();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current;
while ((current = bis.read()) != -1)
{
baf.append((byte) current);
}
return new String (baf.toByteArray());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
감사합니다,하지만 난 내 코드에이 코드를 붙여 넣기 한 후 여기에서 확인할 수 있습니다. 나는 1 개의 방법 (연결)을 오버라이드해야한다. ucon.addRequestProperty ("x-api-key", apiKey);를 추가해야합니다. 이 방법 안에요? 또는 늦었을 때 이미 연결이 설정되어 있습니까? – Timmeeh93
URLConnection은 반드시 HTTP를 사용하지 않고'connect()'구현을하지 않기 때문에 ('HttpURLConnection'과는 달리) 제 대답을 업데이트했습니다. 여러분은'HttpURLConnection'을 사용해야합니다. –
하지만 HttpURLConnection (URL) 유형을 인스턴스화 할 수 없다는 오류가 나타납니다. 나는 이클립스가하고 싶은 말 위에 내 포스트를 업데이트 할 것이다. – Timmeeh93