使用HttpUrlConnection将请求发布到服务器 [英] Post request to server using HttpUrlConnection

查看:134
本文介绍了使用HttpUrlConnection将请求发布到服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我被困在两者之间.我想使用HttpUrlConnection实现POST方法,以发布用于将用户注册到服务器的电子邮件,名称和密码. 这是我的代码:

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

空格后的"0"是http响应代码返回的响应代码. 在浏览器中尝试输入URL时,URL是正确的. 我不知道我在哪里犯错;是我的服务器故障还是代码错误,因为我认为我的代码没有任何交互处理.

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.

我是Android Developement的初学者,曾尝试过很多次,使用了不同的代码,但出错了.

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

请帮助! 预先感谢.

推荐答案

尝试如下操作:

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

这篇关于使用HttpUrlConnection将请求发布到服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆