I wanted to build a small application that would get weather data by sending a URL request to weatherapi.com. However, I ran into a problem. Here is my code:
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);
}
}
}
I passed the API key through the header, but I can't pass the city data the same way. Output:
HTTP/1.1 400 Bad Request
3b
{"error":{"code":1003,"message":"Parameter q is missing."}}
0
CodePudding user response:
Use:
w.write("GET /v1/current.json?q=London HTTP/1.1\r\n");
Btw: In HTTP the headers are separated from the body payload by a blank line. In your current code „q“ is an additional header.