jitendra
jitendra

Reputation: 1458

Sending POST json from Android and receiving on Django

I am trying to get an android app to interact with a server in Django.
The app is trying to POST "json" data to Django. However, I am unable to receive the object on the Django end. The value of request.POST is <QueryDict: {}> although the data sent isn't blank. Following is the code snippet for POST request from android.

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

EDIT:
Earlier, I was getting CSRF error and handled it this way (I haven't worked with Django enough to know if this is correct way to handle CSRF error)

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

Any help with rectifying the problem would be highly appreciated.

Upvotes: 1

Views: 3138

Answers (1)

Gerard
Gerard

Reputation: 9408

OK I'm not very fluent in java but it seems to me that your request is well formed.

I think the issue is that you are sending the data as a json string instead of as if it was a raw form. When you do it this way, the data is not displayed in request.POST but in request.body as what it is: a json string, not form-like data.

So I think you have to take one of these ways:

  1. send the data from the Android app as a form (not json-like). This way you'll see it in request.POST or
  2. translate request.body into a dict and work with it instead of request.POST

Hope this helps! :)

Upvotes: 5

Related Questions