我如何从我的inputreader.read()中读取数据?

时间:2018-09-11 08:17:17

标签: java

public static boolean sendRequest(String request) {
    InputStream inputStream = null;
    try {
        URL url = new URL(request);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setReadTimeout(TIMEOUT);
        connection.setConnectTimeout(TIMEOUT);
        connection.setRequestMethod("POST");
        connection.connect();
        inputStream = connection.getInputStream();
        while (inputStream.read() != -1);
        return true;
    } catch (IOException error) {
        return false;
    } finally {
        try {
            if (inputStream != null) {
                inputStream.close();
            }
        } catch (IOException secondError) {
            Log.w(RequestManager.class.getSimpleName(), secondError);
        }
    }
}

如何从inputreader.read()读取数据?我想读取从服务器发回的数据

2 个答案:

答案 0 :(得分:0)

这可能有用。

import java.net.*;
import java.io.*;

public class URLConnectionReader {
    public static void main(String[] args) throws Exception {
        URL oracle = new URL("http://www.oracle.com/");
        URLConnection yc = oracle.openConnection();
        BufferedReader in = new BufferedReader(new InputStreamReader(
                                yc.getInputStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) 
            System.out.println(inputLine);
        in.close();
   }
}

作为参考,您可以从链接https://docs.oracle.com/javase/tutorial/networking/urls/readingWriting.html中查找。

答案 1 :(得分:0)

int iReadSize;
byte[] buffer = new byte[4096];

try (InputStream inputStream = connection.getInputStream();) {
    while ((iReadSize = inputStream.read(buffer)) != -1) {
        System.out.println(new String(buffer, 0, iReadSize));
    }
} catch (IOException error) {
}