使用HttpUrlConnection向服务器发布请求

时间:2016-06-23 16:31:14

标签: android post http-post httpurlconnection http-response-codes

我被困在中间。我想使用HttpUrlConnection实现一个POST方法来发布用于向服务器注册用户的电子邮件,名称和密码。 这是我的代码:

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();
    }
}

我不知道我在哪里弄错了。我得到了以下回复

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

其中&#34; 0&#34;空格后是http响应代码返回的响应代码。 我在浏览器中尝试时,我的网址是正确的。 我不知道我在哪里弄错了;这是我的服务器故障还是我的代码中有错误,因为我认为我的代码没有任何交互处理。

我是Android Developement的初学者,尝试了多次和不同的代码,但收到了错误。

请帮忙! 提前谢谢。

1 个答案:

答案 0 :(得分:2)

尝试这样的事情:

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();
    }
}