HttpClient POST数据到服务器未读取的RESTful API数据

时间:2014-08-05 15:26:06

标签: android django rest django-rest-framework androidhttpclient

我尝试向RestFul服务(带有Rest Framework的django)发送Http帖子。 GET方法工作正常,但POST方法给我带来了问题。我认为这可能是凭据问题或字符串格式问题。这是Android REST客户端代码。

        HttpPost request = new HttpPost(urlString);

        String encoding = Base64
                .encodeToString(new String("username":"password")
                .getBytes(), Base64.DEFAULT);

        request.setHeader("Authorization", "Basic " + encoding);
        request.setHeader("Content-type", "application/json");

        JSONObject obj = new JSONObject();
        obj.put("username", "apple");
        obj.put("pw", "apple");
        obj.put("email", "apple@gmail.com");
        obj.put("name", "apple");

        System.out.println(obj.toString());
        StringEntity entity = new StringEntity(obj.toString());
        entity.setContentType("application/json");

        request.setEntity(entity);
        // Send request to WCF service
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpResponse response = httpClient.execute(request);

        // Get the status of web service
        BufferedReader rd = new BufferedReader(new InputStreamReader(
                response.getEntity().getContent()));
        // print status in log
        String line = "";
        while ((line = rd.readLine()) != null) {
            Log.d("Status Line", "Webservice: " + line);
        }

这是Android aplog:

I/System.out﹕ {"email":"apple@gmail.com","username":"apple","name":"apple","pw":"apple"}

D/Status Line﹕ Webservice: {"username": ["This field is required."], "email": ["This field is required."], "pw": ["This field is required."], "name": ["This field is required."]}

这里是来自Django服务器的日志:

[05/Aug/2014 15:09:39] "POST /split/api_post_user/ HTTP/1.1" 400 151

我也尝试过CURL,以下脚本运行正常。

curl -u username:password -X POST \
--data '{"username" : "apple" , "pw" : "12345", "email" : "abc@gmail.com", "name" : "John" }' \
-H "Content-Type:application/json" \
$URL

logcat的第二行是来自服务器的响应。 例如,如果我使用错误的用户/密码对。它会给我

[Webservice: {"detail": "Invalid username/password"}]. 

如果我省略了setHeader("授权")部分,它会给我

[Webservice: {"detail": "Authentication credentials were not provided."}] 

2 个答案:

答案 0 :(得分:1)

在“活动类”

中的代码下面尝试以下代码..place
class PlaceOrder extends AsyncTask<Void, Void, Void> {

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

            // TODO Auto-generated method stub

            try {

                HttpClient httpClient = new DefaultHttpClient();

                HttpPost httpPst = new HttpPost(

                "yout_url");

                ArrayList<NameValuePair> parameters = new ArrayList<NameValuePair>(

                2);

                parameters.add(new BasicNameValuePair("username", "apple"));

                parameters.add(new BasicNameValuePair("pw", "apple"));

                parameters.add(new BasicNameValuePair("email",
                        "apple@gmail.com"));

                parameters.add(new BasicNameValuePair("name", "apple"));

                httpPst.setEntity(new UrlEncodedFormEntity(parameters));

                HttpResponse httpRes = httpClient.execute(httpPst);

                String str = convertStreamToString(
                        httpRes.getEntity().getContent()).toString();

                Log.i("mlog", "outfromurl" + str);

            } catch (UnsupportedEncodingException e) {

                // TODO Auto-generated catch block

                e.printStackTrace();

            } catch (ClientProtocolException e) {

                // TODO Auto-generated catch block

                e.printStackTrace();

            } catch (IOException e) {

                // TODO Auto-generated catch block

                e.printStackTrace();

            }

            return null;

        }

    }

    public static String convertStreamToString(InputStream is) {

        BufferedReader reader = new BufferedReader(new InputStreamReader(is));

        StringBuilder sb = new StringBuilder();

        String line = null;

        try {

            while ((line = reader.readLine()) != null) {

                sb.append(line + "\n");

            }

        } catch (Exception e) {

            e.printStackTrace();

        } finally {

            try {

                is.close();

            } catch (IOException e) {

                e.printStackTrace();

            }

        }

        return sb.toString();

    }

从您的 onCreate 方法

调用new PlaceOrder().execute();

答案 1 :(得分:0)

我通过更改解码密码来解决问题。

    String encoding = Base64
            .encodeToString(new String("username":"password")
            .getBytes(), Base64.URL_SAFE|Base64.NO_WRAP);