从 Android 发送 POST json 并在 Django 上接收

jit*_*dra 1 django post android

我正在尝试让一个 android 应用程序与 Django 中的服务器进行交互。
该应用程序正在尝试将“json”数据发布到 Django。但是,我无法在 Django 端接收对象。尽管发送的数据不是空的,但其值为request.POSTis <QueryDict: {}>。以下是来自 android 的 POST 请求的代码片段。

public static String POST(String url,JSONObject obj){
    InputStream inputStream = null;
    String result = "";
    try{            
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        String json = obj.toString();
        StringEntity se = new StringEntity(json);
        httpPost.setEntity(se);

        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type","application/json");

        HttpResponse httpResponse = httpClient.execute((HttpUriRequest)httpPost);
        inputStream = httpResponse.getEntity().getContent();

        if(inputStream!=null){
            result = convertInputStreamToString(inputStream);
        }else{
            result = "Did not work!";
        }
    }catch(Exception e){

    }

    return result;
}
Run Code Online (Sandbox Code Playgroud)

编辑
早些时候,我收到 CSRF 错误并以这种方式处理它(我还没有与 Django 合作过,无法知道这是否是处理 CSRF 错误的正确方法)

@csrf_exempt
def search(request):  
  logger.debug(request.POST)
  """Code for JSON object processing"""
Run Code Online (Sandbox Code Playgroud)

任何解决问题的帮助将不胜感激。

Ger*_*ard 5

好的,我对 Java 不是很流利,但在我看来,您的请求格式良好。

我认为问题在于您将数据作为 json 字符串而不是原始形式发送。当您这样做时,数据不会显示在其中,request.POST而是按request.body原样显示:json 字符串,而不是类似表单的数据。

所以我认为你必须采取以下方式之一:

  1. 将 Android 应用程序中的数据作为表单(不是类似 json 的)发送。这样你会看到它在request.POST
  2. 转换request.body为 adict并使用它而不是request.POST

希望这可以帮助!:)