gpt4 book ai didi

java - 从 URL 获取 xml

转载 作者:行者123 更新时间:2023-12-01 22:43:21 25 4
gpt4 key购买 nike

我正在尝试从服务器下载 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 文档的请求的任何线索吗?

最佳答案

如果返回“未知主机”,则同一 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");

关于java - 从 URL 获取 xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25761916/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com