我想構建一個小型應用程式,通過向 weatherapi.com 發送 URL 請求來獲取天氣資料。但是,我遇到了一個問題。這是我的代碼:
import java.io.*;
import java.util.*;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
public class WeatherService {
public static void main(String[] args) throws IOException {
Properties mavenProperties = new Properties();
InputStream propertiesStream = WeatherService.class.getResourceAsStream("/maven.properties");
mavenProperties.load(propertiesStream);
final String API_KEY = mavenProperties.getProperty("api.key");
SSLSocketFactory factory = (SSLSocketFactory) SSLSocketFactory.getDefault();
try (SSLSocket socket = (SSLSocket)factory.createSocket("api.weatherapi.com", 443)) {
socket.startHandshake();
Writer w = new OutputStreamWriter(socket.getOutputStream());
w.write("GET /v1/current.json HTTP/1.1\r\n");
w.write("Host: api.weatherapi.com\r\n");
w.write("Key: " API_KEY "\r\n");
w.write("q: London\r\n");
w.write("\r\n");
w.flush();
InputStream in = socket.getInputStream();
int b;
while ((b = in.read()) != -1)
System.out.write(b);
}
}
}
我通過標頭傳遞了 API 密鑰,但我不能以同樣的方式傳遞城市資料。輸出:
HTTP/1.1 400 Bad Request
3b
{"error":{"code":1003,"message":"Parameter q is missing."}}
0
uj5u.com熱心網友回復:
利用:
w.write("GET /v1/current.json?q=London HTTP/1.1\r\n");
順便說一句:在 HTTP 中,標頭與正文有效負載之間用空行分隔。在您當前的代碼中,“q”是一個附加標題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/528610.html
標籤:爪哇http网址
