通过HttpUrlConnection在服务器上注册用户数据的Post请求



我目前正在一个项目中工作,我需要发送用户名,密码和用户的电子邮件,以便在我的服务器上注册用户。我使用POST命令,因为我必须发送3个值注册一个用户,我使用ContentValues为此目的。下面是我的代码:

@Override
    protected String doInBackground(String... params) {
        try {
            url = new URL(params[0]);
            httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setDoInput(true);
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setRequestMethod("POST");
            ContentValues values = new ContentValues();
            values.put("email", "abc@xyz.com");
            values.put("password", "123");
            values.put("name","ABC");
            outputStream = httpURLConnection.getOutputStream();
            bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
            bufferedWriter.write(getQuery(values));
            bufferedWriter.flush();
            statusCode = httpURLConnection.getResponseCode();
            Log.i("Result",String.valueOf(statusCode));
            inputStream = new BufferedInputStream(httpURLConnection.getInputStream());
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            int data = inputStreamReader.read();
            while (data != -1) {
                char current = (char) data;
                result += current;
                data = inputStreamReader.read();
            }
            JSONObject jsonObject = new JSONObject(result);
            Log.i("Result",String.valueOf(jsonObject));
            if (statusCode == 200) {
                inputStream = new BufferedInputStream(httpURLConnection.getInputStream());
                Log.i("Result","Correct Data Returned");
                JSONObject jsonObject = new JSONObject(response);
                return true;
            } else {
                Log.i("Result","Data not returned");
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

这是我的getQuery方法:

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());
        return result.toString();
    }

但是我得到了以下的响应:

Result: name=ABC&email=abc%40xyz.com&password=123
Result: 422
System.err: java.io.FileNotFoundException: http://docpanel.myworkdetails.com/api/auth/register

422是responseCode返回的状态码,意思是:

"errors": {
     "email": [
       "The email field is required."
     ],
     "password": [
       "The password field is required."
     ],
     "name": [
       "The password field is required."
     ]
   },
   "status_code": 422

我不知道如何通过POST方法传递参数,以便使我的注册页面工作。我有正确的URL。

是服务器端故障还是我在实现POST时犯了错误?

请帮忙!

为什么不直接将url与参数连接起来呢?

请求看起来像这样:"http://example.com/test?param1=a& param2 = b& param3 = c"

你可以使用HttpPost而不是HttpURLConnection

        final HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, Constants.CONNECTION_TIMEOUT);
        HttpClient httpClient = new DefaultHttpClient(httpParams);
        HttpPost httpPost = new HttpPost("yourBackendUrl");
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("key","value"));
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpClient.execute(httpPost);
        InputStream inStream = response.getEntity().getContent();
        builder = new StringBuilder();
        BufferedReader reader = new BufferedReader(new InputStreamReader(inStream));
        String line;
        while ((line = reader.readLine()) != null) {
            builder.append(line);
        }
        JSONObject json = new JSONObject(builder.toString());

已解决

我犯了错误,我没有在正确的地方添加httpUrlConnection.connect()httpURLConnection.setRequestProperty("Accept","/")在正确的地方使其工作正常。下面是使用HttpUrlConnection的POST请求使注册页面成为可能的正确代码:

protected String doInBackground(String... params) {
        try {
            url = new URL(params[0]);
            httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setDoInput(true);
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setRequestProperty("Accept","*/*");
            ContentValues values = new ContentValues();
            values.put("email", "abc@tjk.com");
            values.put("password", "hjh");
            values.put("name","hui");
            httpURLConnection.connect();
            outputStream = httpURLConnection.getOutputStream();
            bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
            bufferedWriter.write(getQuery(values));
            bufferedWriter.flush();
            statusCode = httpURLConnection.getResponseCode();
            inputStream = httpURLConnection.getInputStream();
            if (statusCode == 200) {
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                int data = inputStreamReader.read();
                while (data != -1) {
                    char current = (char) data;
                    result += current;
                    data = inputStreamReader.read();
                }
                JSONObject jsonObject = new JSONObject(result);
                Log.i("Result",String.valueOf(jsonObject));
            } else {
                Log.i("Result","false");
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

相关内容

  • 没有找到相关文章

最新更新