Post request to server using HttpUrlConnection

2019-07-14 00:43发布

问题:

I am stuck in between. I want to implement a POST method using HttpUrlConnection to Post the email,name and password for registering a user to the server. Here is my code :

public void createNewProfile(View view){

    new Post().execute("http://myurl.com");

}

private class Post extends AsyncTask<String, Void, String>{

    @Override
    protected String doInBackground(String... params) {

        try {

            URL url = new URL("http://myurl.com");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);

            ContentValues values = new ContentValues();
            values.put("email", "abc@xyz.com");
            values.put("password", 123);
            values.put("name","ABC");

            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(getQuery(values));
            writer.flush();
            writer.close();
            os.close();
            response = conn.getResponseCode();
            conn.connect();

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Log.i("Result",String.valueOf(e));
        }
        return null;
    }

    private String getQuery(ContentValues values) throws UnsupportedEncodingException
    {
        StringBuilder result = new StringBuilder();
        boolean first = true;

        for (Map.Entry<String, Object> entry : values.valueSet())
        {
            if (first)
                first = false;
            else
                result.append("&");

            result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(String.valueOf(entry.getValue()), "UTF-8"));
        }

        Log.i("Result",result.toString() +" "+ String.valueOf(response));

        return result.toString();
    }
}

I don't know where I am making mistake. I am getting following response

name=ABC&email=abc%40xyz.com&password=123 0

Where "0" after space is response code returned by http response code. While my URL is correct when I am trying it in the browser. I don't know where I am making mistake; Is it my server fault or there is mistake in my code because I don't think there is any interaction processing by my code.

I am beginner in Android Developement, tried many times and different codes,but getting error.

Please Help! Thanks in advance.

回答1:

Try something like this:

try {
    url = new URL(params[0]);
    httpURLConnection = (HttpURLConnection) url.openConnection();
    httpURLConnection.setDoInput(true);
    httpURLConnection.setDoOutput(true);
    httpURLConnection.setRequestMethod("POST");



    outputStream = httpURLConnection.getOutputStream();

    bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
    bufferedWriter.write(myValues);
    bufferedWriter.flush();

    int statusCode = httpURLConnection.getResponseCode();
    Log.d(Constants.LOG_TAG, " The status code is " + statusCode);

    if (statusCode == 200) {
        inputStream = new BufferedInputStream(httpURLConnection.getInputStream());
        response = convertInputStreamToString(inputStream);
        Log.d(Constants.LOG_TAG, "The response is " + response);

        JSONObject jsonObject = new JSONObject(response);

return true;

    } else {
        return false;
    }

} catch (Exception e) {

    e.printStackTrace();
} finally {
    try {
        if (inputStream != null) {
            inputStream.close();
        }
        if (outputStream != null) {
            outputStream.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}