【问题标题】:HttpClient POST data to RESTful API data not being read by the serverHttpClient POST 数据到服务器未读取的 RESTful API 数据
【发布时间】:2014-08-08 13:44:46
【问题描述】:

我尝试向 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("Authorization") 部分,它会给我

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

【问题讨论】:

  • 那个logcat基本上就是完整的logcat。这段 android 代码将在主要活动的 onCreate() 中的 Asynctask 中运行。我还尝试在另一个 api 上执行 GET 方法(不需要用户名/密码),它工作正常。
  • 我无法理解你的日志
  • 嗯...感谢您的帮助。对不起,令人困惑的 logcat。我打印了两行。第一行是 JSONObject.toString()。第二行是来自 Django Rest 服务器的响应。
  • 是的,正确的反应令人困惑
  • 我更新了问题。谢谢。

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


【解决方案1】:

试试下面的代码..将下面的代码放在你的活动类中

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

【讨论】:

  • 谢谢。我一回到家就试试这个,然后告诉你。非常感谢!
  • 嗯......它不起作用。输出: I/mlog﹕outfromurl{"username": ["This field is required."], "email": ["This field is required."], "pw": ["This field is required."] , "name": ["此字段为必填项。"]}
【解决方案2】:

我通过更改解码密码的代码解决了这个问题。

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

【讨论】:

    猜你喜欢
    • 2013-11-23
    • 2015-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-13
    • 1970-01-01
    • 2018-06-17
    相关资源
    最近更新 更多