【问题标题】:Connection to server is ok, but I'm writing an empty string to the OutputStream连接到服务器没问题,但我正在向 OutputStream 写入一个空字符串
【发布时间】: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


【解决方案1】:

HttpURLConnection 有一个糟糕的 API,使用起来非常混乱。我强烈建议使用OkHttp 代替它。使用OkHttp,您将使用以下代码发出请求:

String parameters = params[0];
Response response;
try {
    MediaType contentType = MediaType.parse("text/plain; charset=utf-8");
    RequestBody body = RequestBody.create(contentType, parameters);
    Request request = new Request.Builder()
        .url("http://www.example.com/login/webhook.php")
        .post(body)
        .build();

    response = client.newCall(request).execute();
    if (response.isSuccessful()) {
        return response.body().string();
    }
} catch (IOException e) {
    Log.d(TAG, "an error occured");
    e.printStackTrace();
} finally {
    if(response != null) {
        response.close();
    }
}
return null;

如果你想坚持使用HttpURLConnectionthis answer 很好地解释了连接过程。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-05-12
    • 2012-04-20
    • 1970-01-01
    • 2016-11-12
    • 1970-01-01
    • 1970-01-01
    • 2010-11-07
    • 1970-01-01
    相关资源
    最近更新 更多