我正在尝试发送HTTP请求以获取响应(TCP-IP),该响应应包含XML。这是我用来发送请求并返回它的方法:
public String getResponse() throws IOException {
String result="";
Socket socket = new Socket(host,port);
//encoding login and password
String username = "root";
String password = "ut72";
String auth = username + ":" + password;
String encodedAuth = Base64.encode(auth.getBytes());
//sending request
PrintWriter request = new PrintWriter( socket.getOutputStream() );
request.print( "GET " + path + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Authorization: Basic " + encodedAuth + "\r\n" +
"Connection: close\r\n\r\n");
request.flush( );
//waiting for response
InputStream inStream = socket.getInputStream( );
BufferedReader rd = new BufferedReader(
new InputStreamReader(inStream));
String line;
while ((line = rd.readLine()) != null) {
result = result+"\n"+line;
}
return result;
}
这是我的主要内容:
public static void main(String[] args) throws URISyntaxException, IOException {
GetDataFromUnidrive getter = new GetDataFromUnidrive("http://192.168.130.182/US/4.02/dynamic/readparval.xml");
String response = getter.getResponse();
System.out.println(response);
以下是我得到的回复:
HTTP/1.1 200 OK
Content-Type: text/xml
Cache-Control: private
Expires: Thu, 26 Oct 1995 00:00:00 GMT
Transfer-Encoding: chunked
Server: Allegro-Software-RomPager/4.01
Connection: close
0
Process finished with exit code 0
如果我猜对了," 0"中间是XML响应。但是......这不是我应该得到的;事实上,如果我在浏览器中键入我的请求,输入" http://192.168.130.182/US/4.02/dynamic/readparval.xml",我得到了这个(这是我想通过我的程序获得的):
有人能解释一下原因可能会导致这个" 0"出现了?
编辑:以下是我正在使用的HttpClient(似乎发生了同样的事情)
String url = "http://192.168.130.182/US/4.02/dynamic/readparval.xml";
HttpClient client = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
System.out.println("Response Code : "
+ response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
String result = "";
String line = "";
while ((line = rd.readLine()) != null) {
result+=line;
}
return result;
这给了我结果:
Response Code : 200
Process finished with exit code 0
当我想要获得更多信息时...(我正在做String result = response.getEntity()。toString();)我得到了这个:
Response Code : 200
ResponseEntityProxy{[Content-Type: text/xml,Chunked: true]}
Process finished with exit code 0
所以我想我仍然得到了一个chuncked tranfert-enconding无论如何......