有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何从InputStream对象读取特定数据?

当我使用HttpUrlConnection对象建立连接时,如何从InputStream对象读取特定数据。我想读取和发布数据,例如,我想读取特定的标签数据,比如等等。就像我想发布的一样

public class Test {

public static void main(String[] args) throws Exception {

    HttpsURLConnection con = (HttpsURLConnection) new URL("some URL ...")
            .openConnection();

    // reading data from connection
    InputStream in = new BufferedInputStream(con.getInputStream());
    System.out.println(readStream(in));

}
private static String readStream(InputStream is) {
    try {
      ByteArrayOutputStream bo = new ByteArrayOutputStream();
      int i = is.read();
      while(i != -1) {
        bo.write(i);
        i = is.read();
      }
      return bo.toString();
    } catch (IOException e) {
      return "";
    }
}

}

请帮忙


共 (2) 个答案

  1. # 1 楼答案

    试试这个,我在我的案例中得到了JSONObject:

    static InputStream is = null;
    
    
                try {
    
                    BufferedReader reader = new BufferedReader(new InputStreamReader(
                            is, "iso-8859-1"), 8);
    
                    StringBuilder sb = new StringBuilder();
    
                    String line = null;
    
                    while ((line = reader.readLine()) != null) {
    
                        sb.append(line + "\n");
    
                    }
    
                    is.close();
    
                    json = sb.toString();
    
                } catch (Exception e) {
    
                    e.printStackTrace();
                }
    
  2. # 2 楼答案

    使用jsouphttp://jsoup.org 它有工具来处理你想用html做的所有事情