0

我目前与一些中间件建立了连接,通过它我将 SQL 查询发送到数据库。

我在将 DataInputStream 转换为可用格式(无论是否为字符串)时遇到了一些麻烦。我查看了另一个 StackOverflow 问题,但是这并没有解决我的问题,因为使用

in.readLine();

被“弃用”,无论这意味着什么。我需要能够从我的中间件读取响应。

private class NetworkTask extends AsyncTask<String, Void, Integer> 
{
    protected Integer doInBackground(String... params)
    {
        Message message = networkHandler.obtainMessage();

        String ip = "example ip";
        int port = 1234;

        try 
        {
            InetAddress serverAddr = InetAddress.getByName(ip);
            Log.d("EventBooker", "C: Connecting...");
            Socket socket = new Socket(serverAddr, port);               

            DataInputStream in = new DataInputStream(socket.getInputStream());


            try 
            {
                Log.d("EventBooker", "C: Connected. Sending command.");
                PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
                out.println(params[0]);
                networkHandler.sendMessage(message);
                Log.d("EventBooker", "C: Sent.");
            } 
            catch (Exception e) 
            {
                Log.e("EventBooker", "S: Error", e);
            }
            Log.d("EventBooker", "C: Reading...");



            Log.d("EventBooker", "C: Response read, closing.");
            socket.close();
            Log.d("Eventbooker", "C: Closed.");
        } 
        catch (Exception e)
        {
            Log.e("EventBooker", "C: Error", e);
        }
        return 1;
    }
}
4

1 回答 1

2

将您的转换DataInputStreamBufferedReaderStream这样的:

BufferedReader d = new BufferedReader(new InputStreamReader(in));

然后你想得到你的实际String,要做到这一点,你做这样的事情:

StringBuffer sb = new StringBuffer();
String s = "";

while((s = d.readLine()) != null) {
    sb.append(s);
}

String data = sb.toString();

//Use data for w/e

轻松简单!

我们不只是将它附加到已经存在的字符串的原因是 JavaStrings是不可变的,因此每次String重新创建对象时都会产生性能问题。因此StringBuffer

于 2013-04-13T14:36:31.243 回答