Tôi đang tạo trình thu thập dữ liệu và cần lấy dữ liệu từ luồng bất kể đó có phải là 200 hay không. CURL đang thực hiện nó, cũng như bất kỳ trình duyệt chuẩn nào.URLConnection không cho phép tôi truy cập dữ liệu trên các lỗi Http (404.500, v.v.)
Sau đây sẽ không thực sự nhận được nội dung của yêu cầu, mặc dù có một số, ngoại lệ được ném với mã trạng thái lỗi http. Tôi muốn đầu ra bất kể, có cách nào không? Tôi thích sử dụng thư viện này vì nó thực sự sẽ thực hiện các kết nối liên tục, điều này hoàn hảo cho loại thu thập dữ liệu mà tôi đang thực hiện.
package test;
import java.net.*;
import java.io.*;
public class Test {
public static void main(String[] args) {
try {
URL url = new URL("http://github.com/XXXXXXXXXXXXXX");
URLConnection connection = url.openConnection();
DataInputStream inStream = new DataInputStream(connection.getInputStream());
String inputLine;
while ((inputLine = inStream.readLine()) != null) {
System.out.println(inputLine);
}
inStream.close();
} catch (MalformedURLException me) {
System.err.println("MalformedURLException: " + me);
} catch (IOException ioe) {
System.err.println("IOException: " + ioe);
}
}
}
Làm việc, nhờ: Đây là những gì tôi đã đưa ra - cũng giống như một bằng chứng sơ bộ khái niệm:
import java.net.*;
import java.io.*;
public class Test {
public static void main(String[] args) {
//InputStream error = ((HttpURLConnection) connection).getErrorStream();
URL url = null;
URLConnection connection = null;
String inputLine = "";
try {
url = new URL("http://verelo.com/asdfrwdfgdg");
connection = url.openConnection();
DataInputStream inStream = new DataInputStream(connection.getInputStream());
while ((inputLine = inStream.readLine()) != null) {
System.out.println(inputLine);
}
inStream.close();
} catch (MalformedURLException me) {
System.err.println("MalformedURLException: " + me);
} catch (IOException ioe) {
System.err.println("IOException: " + ioe);
InputStream error = ((HttpURLConnection) connection).getErrorStream();
try {
int data = error.read();
while (data != -1) {
//do something with data...
//System.out.println(data);
inputLine = inputLine + (char)data;
data = error.read();
//inputLine = inputLine + (char)data;
}
error.close();
} catch (Exception ex) {
try {
if (error != null) {
error.close();
}
} catch (Exception e) {
}
}
}
System.out.println(inputLine);
}
}
"InputStream is = connection.getResponseMessage();" Tôi không thấy phương thức getResponseMessage trong lớp URLConnection, nó là một phần của HttpUrlConnection, vì vậy chúng ta không nên định kiểu đó? Hoặc chúng ta có thể thay thế getResponseMessage bằng getInputStream, hoặc sẽ ném ngoại lệ? – David
Đó là lỗi đánh máy, đó là 'connection.getInputStream()'. –
Câu trả lời rất hay và ngắn –