Staram się odebrać dane z strony http://openweathermap.org/api
Zgodnie z instrukcją http://openweathermap.org/api zarejestrowalem się na strone, pobralem klucz i dodalem go jako atrybut url
Na początku chciałem zrobić to jak najbardziej surowo:
public String getWeather(String miasto){
Socket soc = null;
PrintWriter writer = null;
BufferedReader reader = null;
try {
soc = new Socket(InetAddress.getByName("api.openweathermap.org"), 80);
System.out.println(soc.isConnected());
writer = new PrintWriter(soc.getOutputStream());
reader = new BufferedReader(new InputStreamReader(soc.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(miasto);
writer.print("GET /data/2.5/weather?q=Warsaw&APPID=1e90436c71c53276dbcc2e72e5a15a60 HTTP/1.1\r\n");
writer.print("Host: api.openweathermap.org\n\r\n");
// ("api.openweathermap.org/data/2.5/weather?q=" + miasto+"&APPID=1e90436c71c53276dbcc2e72e5a15a60");
writer.flush();
String txt = "";
try {
int counter = 1;
while((txt = reader.readLine()) != null) {
System.out.println(counter++ + ": "+ txt);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
};
writer.close();
try {
reader.close();
soc.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
i gdy testuje to dziala lecz zatrzymuje się w lini 11 i po jakiś 30 sekundach zwraca dopiero linie z JSON-em.
consola:
true
Warsaw
1: HTTP/1.1 200 OK
2: Server: openresty
3: Date: Sun, 01 Apr 2018 08:53:00 GMT
4: Content-Type: application/json; charset=utf-8
5: Content-Length: 516
6: Connection: keep-alive
7: X-Cache-Key: /data/2.5/weather?APPID=1e90436c71c53276dbcc2e72e5a15a60&q=warsaw
8: Access-Control-Allow-Origin: *
9: Access-Control-Allow-Credentials: true
10: Access-Control-Allow-Methods: GET, POST
11: //tu program zatrzymuje się i od kilkunastu do kilkudziesięciu sekundach oczekiwania zwraca JSON-a
12: {"coord":{"lon":21.01,"lat":52.23},"weather":[{"id":300,"main":"Drizzle","description":"light intensity drizzle","icon":"09d"},{"id":701,"main":"Mist","description":"mist","icon":"50d"}],"base":"stations","main":{"temp":279.15,"pressure":991,"humidity":93,"temp_min":279.15,"temp_max":279.15},"visibility":2500,"wind":{"speed":6.7,"deg":270},"clouds":{"all":90},"dt":1522571400,"sys":{"type":1,"id":5374,"message":0.0023,"country":"PL","sunrise":1522555813,"sunset":1522602618},"id":756135,"name":"Warsaw","cod":200}
Moje pytanie to dlaczego? jak to naprawić z uyciem socketu?
i jak to zrobi najefektywniej korzystajc z JAVA SE