Björn
Björn

Reputation: 67

GET xml from URL

I'm trying to download a XML document from a server:

http://api.yr.no/weatherapi/locationforecast/1.9/?lat=60.10;lon=9.58;msl=70

Im using java to do this and using sockets is required aswell.

import java.net.*;
import java.io.*;

public class main 
{

/**
 * @param args
 */
public static void main(String[] args) 
{
    try
    {
        byte[] data = new byte[100000];
        Socket clientSocket = new Socket();
        InetSocketAddress ip = new InetSocketAddress("api.yr.no", 80);
        clientSocket.connect(ip);
        DataInputStream inData = new DataInputStream(clientSocket.getInputStream());
        OutputStream outData = clientSocket.getOutputStream();

        PrintWriter pw = new PrintWriter(outData, false);
        pw.print("GET " + "/weatherapi/locationforecast/1.9/?lat=60.10;lon=9.58;msl=70" + " HTTP/1.0\r\n");
        pw.print("\r\n");
        pw.flush();

        int bytesread = inData.read(data);
        String translateddata = new String(data);
        System.out.print(translateddata);
    } 
    catch (IOException e) 
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    finally
    {

    }
}

However after running this i dont get the xml at the URL i get:

HTTP/1.1 404 Unkown host
Server: Varnish
Content-Type: text/html; charset=utf-8
Content-Length: 395
Accept-Ranges: bytes
Date: Wed, 10 Sep 2014 09:16:22 GMT
X-Varnish: 1432508106
Age: 0
Via: 1.1 varnish
Connection: close


<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
 #http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
  <head>
    <title>404 Unkown host</title>
  </head>
  <body>
    <h1>Error 404 Unkown host</h1>
    <p>Unkown host</p>
    <h3>Guru Meditation:</h3>
    <p>XID: 1432508106</p>
    <hr>
    <p>Varnish cache server</p>
  </body>
</html>

So I'm guessing my GET request is wrong somehow, but I'm having trouble locating the problem. Any clues on how to build a request for this XML document?

Upvotes: 0

Views: 132

Answers (2)

Steffen Ullrich
Steffen Ullrich

Reputation: 123531

If you get "unknown host" back, there will probably be multiple hosts behind the same IP. In this case add a Host-Header, i.e.

pw.print("GET " + "/weatherapi/locationforecast/1.9/?lat=60.10;lon=9.58;msl=70" + " HTTP/1.0\r\n");
pw.print("Host: api.yr.no\r\n");
pw.print("\r\n");

Upvotes: 2

shazin
shazin

Reputation: 21903

Try the following code.

try
{
    URL url = new URL("http://api.yr.no/weatherapi/locationforecast/1.9/?lat=60.10;lon=9.58;msl=70");
    URLConnection yc = url.openConnection();
    BufferedReader in = new BufferedReader(new InputStreamReader(
                                yc.getInputStream()));
    String inputLine;
    while ((inputLine = in.readLine()) != null) {
        System.out.println(inputLine);
    }
    in.close();
} catch(Exception e) {

}

Upvotes: 1

Related Questions