3

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!

8
  • are you sure the request JSON has a child with key of "user_id"? Commented Mar 30, 2014 at 20:48
  • Can you paste more code? There are 2 things to check, have to consumed the response of the previous request fully and also have you released the connection correctly. Commented Mar 31, 2014 at 4:56
  • @kupsef, I am definite that the request json has a child with key 'user_id' since it works perfectly with most mobile clients. Also, to make sure I reversed the order in which I retrieve the keys, to no effect. Commented Apr 1, 2014 at 5:59
  • @NeerajKrishna, I edited the question with more server and client side code. Let me know if you need any other information. Thanks! Commented Apr 1, 2014 at 6:19
  • Why don't you try to print out the request.json for debugging purposes? Commented Apr 1, 2014 at 12:37

1 Answer 1

5

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 :)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.