[英]Buffer with bufferedreader.readLine () returns null unexpectedly
I have problems using BufferedReader when I use readLine ()
it returns null value. 我在使用
readLine ()
时返回NULL值时使用BufferedReader时遇到问题。 This is my code: 这是我的代码:
How can I discover the source of the problem? 我如何发现问题的根源?
BackgroundTask_GET.java BackgroundTask_GET.java
public class BackgroundTask_GET extends AsyncTask<Void, Void, Void> {
String duongdan = MainActivity.SERVER_NAME;
TextView tvResult;
String strName, strScore;
String str;
ProgressDialog pDialog;
Context context;
public String TAG = "GG";
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(context);
pDialog.setMessage("Sending...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
public BackgroundTask_GET(Context context, TextView tvResult, String
strName, String strScore) {
this.tvResult = tvResult;
this.strName = strName;
this.strScore = strScore;
this.context = context;
}
@Override
protected Void doInBackground(Void... voids) {
duongdan += "?name=" + this.strName + "&score=" + this.strScore;
try {
URL url = new URL(duongdan);
HttpURLConnection urlConnection = (HttpURLConnection)
url.openConnection();
BufferedReader bfr = new BufferedReader(new
InputStreamReader(url.openStream()));
String line = "";
StringBuffer sb = new StringBuffer();
Log.d(TAG, "bfr:" + urlConnection);
while ((line = bfr.readLine()) != null) {
sb.append(line);
Log.d(TAG, "append"+sb.append(line));
}
str = sb.toString();
urlConnection.disconnect();
Log.d(TAG, "doInBackground: " + str);
} catch (MalformedURLException e) {
e.printStackTrace();
Log.d(TAG, "exception " + e);
} catch (IOException e) {
e.printStackTrace();
Log.d(TAG, "exception " + e);
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (pDialog.isShowing()) {
pDialog.dismiss();
}
tvResult.setText(str);
Log.d("RESULT", "khanh" + str);
}
} }
`` `MainActivity ```MainActivity
public class MainActivity extends AppCompatActivity implements
View.OnClickListener {
public static final String SERVER_NAME =
"http://192.168.1.2/AndroidNetworking_server/student_GET.php";
private EditText edtName, edtScore;
private Button btnSend;
private TextView tvResult;
String strName, strScore;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edtName = findViewById(R.id.edtName);
edtScore = findViewById(R.id.edtScore);
btnSend = findViewById(R.id.btnSend);
tvResult = findViewById(R.id.tvResult);
btnSend.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch(view.getId()) {
case R.id.btnSend:
strName = edtName.getText().toString();
strScore = edtScore.getText().toString();
BackgroundTask_GET backgroundTask = new
BackgroundTask_GET(this, tvResult, strName, strScore);
backgroundTask.execute();
break;
}
}
}
Error: ~ 错误:〜
` 1 `
2019-07-15 14:07:58.065 24764- 28936/com.example.lab2_khanhpd02377_androidnetworkingD/GG:bfr:com.android.okhttp.internal.huc.HttpURLConnectionImpl: http://192.168.1.2/AndroidNetworking_server/student_GET.php?name=4&score=5 ~ ` 1 `
1`2019-07-15 14:07:58.065 24764- 28936 / com.example.lab2_khanhpd02377_androidnetworkingD / GG:bfr:com.android.okhttp.internal.huc.HttpURLConnectionImpl: http : //192.168.1.2/AndroidNetworking_server/student_GET .php?name = 4&score = 5〜
` 2 `
2019-07-15 14:07:58.066 24764- 28936/com.example.lab2_khanhpd02377_androidnetworking D/GG: doInBackground: ` 2 `
2`2019-07-15 14:07:58.066 24764- 28936 / com.example.lab2_khanhpd02377_androidnetworking D / GG:doInBackground:
I can see a couple of problems with your code: 我可以看到您的代码有几个问题:
The readLine()
method returns the line with the line separator removed . readLine()
方法返回删除了行分隔符的行。 So 所以
while ((line = bfr.readLine()) != null) { sb.append(line); }
will strip line separators while reading. 读取时会剥离行分隔符。
You are not checking the HTTP response code. 您没有检查HTTP响应代码。 If the response code is not a 2xx code, then
getInputStream()
will throw an exception. 如果响应代码不是2xx代码,则
getInputStream()
将引发异常。
The response code can be found using getResponseCode()
. 可以使用
getResponseCode()
找到响应代码。 The error response body can be read using getErrorStream()
. 可以使用
getErrorStream()
读取错误响应主体。
As @user207421 says, you shouldn't call urlConnection.disconnect()
unless you really need to disconnect. 正如@ user207421所说,除非真正需要断开连接,否则不应调用
urlConnection.disconnect()
。 If you don't need to, it is better to let the HTTP client library deal with disconnection. 如果不需要,最好让HTTP客户端库处理断开连接。 (It may be able to keep the connection open, and use it for later requests to the same server.)
(它可能能够保持连接打开,并用于以后对同一服务器的请求。)
You should 1 close the BufferedReader
, and ideally you should do it using try-with-resources . 您应该 1关闭
BufferedReader
,理想情况下,应该使用try-with-resources进行操作 。
1 - I won't say must because there are scenarios where it won't matter. 1-我不会说必须,因为在某些情况下它并不重要。 However, if you don't close the stream, one way or another, you will leak file descriptors which could lead to errors later on.
但是,如果不以一种或另一种方式关闭流,则将泄漏文件描述符,这可能会在以后导致错误。 And, it is certainly good practice to close streams ... because you never really know if your code might be used / reused in the future in some context where the resource leak does matter.
而且,关闭流当然是个好习惯……因为您永远不会真正知道将来在资源泄漏确实很重要的情况下是否可以使用/重用您的代码。
UPDATE - I think you are saying that the real real cause for the null
/ empty stream was on the PHP side. 更新 -我想您是说
null
/空流的真正真正原因是在PHP方面。 Notwithstanding that, you probably ought to address the four issues that I mentioned: line separators, response code, disconnect and using try-with-resource. 尽管如此,您可能应该解决我提到的四个问题:行分隔符,响应代码,断开连接和使用try-with-resource。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.