aadharjain
aadharjain

Reputation: 31

Flask POST 400 Error on accessing request JSONObject

I am working on a android application wherein the android mobile client communicates with the server via a Flask REST API. A particular mobile device intermittently receives 400 response from the server for one of the POST endpoints.

Following is the related server side code:

def post(self):
            app.logger.info("Request :" + request.url)
            if request.headers['Content-Type'] == "application/json":
                    tok = str(request.json['tok'])
                    user_id = str(request.json['user_id'])
                    contact = str(request.json['contact'])   
                    .
                    .
                    .
            else:
                    response = jsonify({"message": "Unsupported Media Type"})
                    response.status_code = 415
                    return response

Response 400 is returned as soon as the request json object is accessed inside the if condition.

Following is the android java code used to encode the json object and execute a post request:

    HttpParams httpParameters = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters,Constants.HTTP_CONNECTION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(httpParameters, Constants.HTTP_SOCKET_TIMEOUT);
    HttpClient client = new DefaultHttpClient(httpParameters);
    URL url = null;
    URI uri = null;
    try {
        url = new URL(Constants.URL+"api/v1/testapi");
        uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
    } catch (MalformedURLException e3) {
        e3.printStackTrace();
    } catch (URISyntaxException e) {
        e.printStackTrace();
    }
    HttpPost post = new HttpPost(uri.toString());
    final JSONObject msgObject = jObject[0];

    StringEntity se = null;
    try {
        se = new StringEntity(msgObject.toString());
    } catch (UnsupportedEncodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));
    post.setEntity(se);
    boolean postFailed = false;
    try {
        HttpResponse response = client.execute(post);
        Log.v(TAG,response.getStatusLine().toString());
        if(response.getStatusLine().toString().indexOf("200")!=-1){
            HttpEntity httpEntity = response.getEntity();
            InputStream is = httpEntity.getContent();
            JSONParser parseJSON = new JSONParser();
            JSONObject JO = parseJSON.getJSONObj(is);
            .
            .
            .

            }
            is.close();

        }else
            postFailed = true; 

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        postFailed = true;
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        postFailed = true;
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        postFailed = true;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        postFailed = true;
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        postFailed = true;
    }

msgObject is of type JSONObject that holds all the expected key value pairs.

The strange part about the issue is that mostly occurs with a particular mobile client (that too intermittently) .Please let me know if you guys have any suggestions on how to resolve this issue. Thanks!

Upvotes: 3

Views: 1999

Answers (1)

akalipetis
akalipetis

Reputation: 928

The best way to say if the correct content type for JSON is been set in Flask is the is_json function. Even if you do not want to use this method for some reason, you should make the if statement like the following

if "application/json" in request.headers["Content-Type"]:

The issue here, is that most of the clients out there do not just put application/json in Content-Type, but also the encoding, so the header results like this:

Content-Type: application/json; charset=utf-8

Hope this clears things now :)

Upvotes: 5

Related Questions