我正在尝试从服务器下载XML文档:
http://api.yr.no/weatherapi/locationforecast/1.9/?lat=60.10;lon=9.58;msl=70
我使用java来执行此操作并且还需要使用套接字。
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
{
}
}
然而,在运行之后,我没有得到URL的xml:
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>
所以我猜测我的GET请求在某种程度上是错误的,但是我无法找到问题所在。关于如何构建对此XML文档的请求的任何线索?
答案 0 :(得分:2)
如果你得到&#34;未知的主人&#34;回来,可能会有多个主机在同一个IP后面。在这种情况下,添加一个Host-Header,即
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");
答案 1 :(得分:1)
请尝试以下代码。
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) {
}