使用HttpUrlConnection向服务器发送POST请求

3

我被卡住了。我想使用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

空格后面的“0”是http响应代码返回的响应代码。 当我在浏览器中尝试我的URL时,它是正确的。 我不知道我犯了什么错误;是我的服务器出了问题还是我的代码有误,因为我不认为我的代码有任何交互处理。

我是Android开发的初学者,尝试了很多次和不同的代码,但是一直出现错误。

请帮忙!提前感谢。


在 finally 语句中获取响应后,请尝试关闭写入器。 - Saeed Jassani
将其设置在 response = conn.getResponseCode() 和 conn.connect() 下面,但是仍然得到相同的响应,我已经删除了它,但是仍然得到相同的响应。 - Swr7der
我已经添加了我的代码作为参考...请检查并告诉我是否有帮助。 - Saeed Jassani
1个回答

3
尝试这样做: ```html

像这样尝试:

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

我现在从这段代码中得到了405响应代码。当我将inputStream运行用于任何响应代码时,又出现了FileNotFoundException。这是我输入的数据格式有问题还是服务器端的错误?我应该尝试使用Volley吗? - Swr7der
你可以尝试使用Volley,但我认为你的URL或服务器端代码存在问题。 - Saeed Jassani
你确定代码没有任何问题吗?我可以使用这个POST请求将特定用户注册到API URL吗? - Swr7der
是的,我已经使用上述代码6个月了。 - Saeed Jassani
关于 POST 请求呢?只需像我在代码中描述的那样查询一些值,就可以用它来注册用户吗? - Swr7der
谢谢 :) 我会做的! - Swr7der

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接