与服务器的连接没问题,但是我要在OutputStream

时间:2017-11-17 22:03:48

标签: android android-asynctask bufferedwriter dataoutputstream

我无法弄清楚这段代码是什么。首先,正如它在这里,它的工作原理。但我担心我错过了一个重要的概念,我不希望它回来后再咬我。我的代码会在我为测试目的而创建的文本日志中写一个空白行,如果我没有添加行" 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;
        }

    }

}

我试图以多种不同的方式提出这个问题,没有人给我任何有用的意见。我想,这是我最后一次尝试简化问题。以上是整个活动。已经建议删除&#39; writer.close()&#39;但那没有用。

提前致谢

1 个答案:

答案 0 :(得分:0)

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可以很好地解释连接过程。