我目前与某些中间件建立了连接,通过该连接我可以将SQL查询发送到数据库。
将DataInputStream转换为可用格式(无论是否为String)时遇到麻烦。我查看了another StackOverflow question,但是由于使用
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;
}
}
最佳答案
像这样将DataInputStream
转换为BufferedReaderStream
:
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
简单容易!
我们之所以不将其附加到已经存在的字符串上,是因为Java
Strings
是不可变的,因此每次重新创建String
对象时,都会造成性能问题。因此,StringBuffer
!