【发布时间】:2017-11-17 22:03:47
【问题描述】:
我不知道这段代码是怎么回事。首先,因为它在这里,它可以工作。但我担心我错过了一个重要的概念,我不希望它以后回来咬我。如果我不添加“connection.getResponseMessage”行,我下面的代码将在我为测试目的创建的文本日志中写入一个空白行。它也适用于“getResponseCode”。为什么?
为什么它在没有这些代码的情况下向 OutputStream 写入一个空缓冲区?
public class AdminActivity extends AppCompatActivity {
Context mContext;
private static final String TAG = "AdminActivity";
EditText mSystemID, mSystemPassword;
RecyclerView mRecyclerView;
Button mUpdateButton, mDownloadButton;
FileItemAdapter mAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin);
mContext = this;
mSystemID = findViewById(R.id.et_system_id);
mSystemPassword = findViewById(R.id.et_system_password);
mRecyclerView = findViewById(R.id.rv_file_names);
mUpdateButton = findViewById(R.id.bt_update_files_list);
mDownloadButton = findViewById(R.id.bt_download_file);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(layoutManager);
DividerItemDecoration divider = new DividerItemDecoration(mContext, layoutManager.getOrientation());
divider.setDrawable(ContextCompat.getDrawable(mContext, R.drawable.divider_dark));
// TESTING TESTING TESTING TESTING TESTING //
mUpdateButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new SendInfoToServer().execute("A new Test");
}
});
}
private static class SendInfoToServer extends AsyncTask<String, String, String> {
HttpURLConnection connection = null; //***** Should eventually change to https instead of http
OutputStream out = null;
@Override
protected String doInBackground(String... params) {
String parameters = params[0];
try {
URL url = new URL("http://www.example.com/login/webhook.php");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.connect();
out = new DataOutputStream(connection.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
writer.write(parameters);
writer.flush();
writer.close();
Log.d(TAG, "response message: " + connection.getResponseMessage());
} catch (IOException e) {
Log.d(TAG, "an error occured");
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
return null;
}
}
}
我尝试以多种不同的方式提出这个问题,但没有人给我任何有用的意见。我想,这是我最后一次尝试简化这个问题。以上是整个Activity。已经有人建议删除“writer.close()”,但没有奏效。
提前致谢
【问题讨论】:
-
我之前告诉过你,你不应该只发送一个文本字符串。但参数与它们的值。你仍然只在文字上乱搞。难怪它不起作用。
-
My code below will write a blank line to a text log。我的上帝..那个文本日志在哪里?在你的服务器上?你为什么不写一个更好的帖子?!是否应该再重复一遍? -
但它确实有效!只要我添加我提到的代码。即使有更好的方法,您仍然应该能够将常规字符串发送到服务器。我只是想解释为什么在 connection.close 之后添加代码有效,以及为什么省略它会导致写入失败。
-
也许你只是不知道
标签: android android-asynctask bufferedwriter dataoutputstream