0
votes

Does anyone have advice on making PUT requests from Android to Django REST Framework? When I post the code below to my API endpoint, specifying the record to be updated (e.g. http://mydomain/api/26), I get a response with status code 200 and the json content of the targeted record, but none of the content has been updated by the request. In contrast, when I make what appears to be an identical request via Postman or via the browsable API, it works fine, giving me the 200 response and the updated json content. Similarly, I can make POST requests to the API using nearly identical Android code with no problem. Any ideas would be wonderful. Thanks.

public static HttpResponse putJsonString(String jsonString, String targetUrl, Context context){
    HttpResponse result = null;
    try {
        HttpParams httpParameters = new BasicHttpParams();
        int timeoutConnection = 3000;
        HttpConnectionParams.setConnectionTimeout(httpParameters,
                timeoutConnection);
        int timeoutSocket = 3000;
        HttpConnectionParams
                .setSoTimeout(httpParameters, timeoutSocket);

        DefaultHttpClient httpclient = new DefaultHttpClient(
                httpParameters);
        HttpPut httpPut = new HttpPut(targetUrl);
        StringEntity se = new StringEntity(jsonString, "UTF-8");
        se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE,
                "application/json"));
        httpPut.setEntity(se);
        httpPut.setHeader("Accept", "application/json");
        httpPut.setHeader("Content-type", "application/json");
        httpPut.setHeader("Authorization", "Token " + PropertyHolder.getUserKey());
        Log.d("put", "put content: " + parseInputStream(context, httpPut.getEntity().getContent()));
        result = httpclient.execute(httpPut);
    } catch (UnsupportedEncodingException e) {
        Util.logError(context, TAG, "error: " + e);
    } catch (ClientProtocolException e) {
        Util.logError(context, TAG, "error: " + e);
    } catch (IOException e) {
        Util.logError(context, TAG, "error: " + e);
    }
    return result;
}
1

1 Answers

0
votes

The solution seems to be simpler than I thought: Make sure there is a trailing slash in the target URL. So http://mydomain/api/26/ instead of http://mydomain/api/26. This does not seem to matter when sending the PUT request from Postman, but from Android, omitting the trailing slash appears to cause the request to be redirected, and in the process it turns into a GET. I think the underlying issue is how the Apache HTTP client handles redirects, and it may be worthwhile to explicitly set this as well, but for now simply adding the slash does the trick.