设置从android客户端到服务器的POST请求

时间:2016-10-27 06:51:01

标签: android httpurlconnection

我正在尝试从Android客户端向服务器发送POST请求。我能够发送GET请求并接收数据,但到目前为止还没有发送POST请求。
我从尝试构建连接的部分得到例外。任何人都可以指出我在这里缺少什么吗? 注意:这是我第二次发送请求,如上所述。所以我使用connection.disconnect();

关闭了第一个连接
public class JSONTask extends AsyncTask<String,String,String> {
        String error = "";
        @Override
        protected String doInBackground(String... params){
            BufferedReader reader = null;
            HttpURLConnection connection = null;

            try {
                URL url = new URL(params[0]);
                connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("POST");
                connection.setDoOutput(true);
                connection.connect();
                OutputStream oStream = connection.getOutputStream();
                BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(oStream, "UTF-8"));
                writer.write(params[1].toString());
                writer.write(params[2].toString());
                writer.close();

                InputStream stream = connection.getInputStream();
                reader = new BufferedReader(new InputStreamReader(stream));
                StringBuffer buffer = new StringBuffer();
                String line = "";
                while ((line = reader.readLine()) != null) {
                    buffer.append(line);
                }
                String response = buffer.toString();
                return response;
            }
            catch(Exception e){
                e.printStackTrace();
            }
            finally
            {
                try
                {
                    reader.close();
                    connection.disconnect();
                }
                catch (Exception e){
                    e.printStackTrace();
                    error = e.getMessage();
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(String result){
            super.onPostExecute(result);
            recvTV.setText(result);
            recvTV.setText(error);
        }
    }


编辑:此函数调用asyncTask。

public void submitQuestion(View view)
    {
        recvTV = (TextView) findViewById(R.id.recvTV2);
        EditText text = (EditText) findViewById(R.id.qTextEditText);
        EditText sId = (EditText) findViewById(R.id.surveyIdET);
        new JSONTask().execute("http://192.168.168.168:3000/users/submitQuestion",text.getText().toString(), sId.getText().toString() );
    }

0 个答案:

没有答案