简体   繁体   中英

HTTP 403 while executing a PUT request

I am creating a django rest api, and I'm trying to send JSON data via PUT request from an Android device, using HttpUrlConnection.

URL url = new URL(myurl);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("PUT");
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
conn.setRequestProperty("Accept", "application/json");
Log.v("Apiput", MainActivity.cookieManager.getCookieStore().getCookies().get(0).toString());
conn.connect();
if(conn.getResponseCode() != 200) {
    return "" + conn.getResponseCode();
}
OutputStreamWriter osw = new OutputStreamWriter(conn.getOutputStream());
osw.write(put);
osw.flush();
osw.close();`

I know I have to send a csrf token, but I think that I'm sending it already. By examining the META in my request I can see the csrf token both in headers and cookies:

'HTTP_COOKIE': 'csrftoken=3jLNzfLIu1P5dBH4WWwggHMH7oDQC7Rx;'

And in my android device i have a CookieManager that says that the csrf cookie has the same value.

V/Apiput﹕ csrftoken=3jLNzfLIu1P5dBH4WWwggHMH7oDQC7Rx

I am getting a 403 (Forbidden) Http error besides the user is authenticated (I can make GET Requests)

[26/Sep/2015 00:16:04]"PUT /api/works/34/ HTTP/1.1" 403 58

With curl I am able to send the request without any problem, with the same user credentials.

I wonder if anyone can tell me what am I doing wrong.

Thanks.

You don't have to set the cookie if you're doing a JSON call to Django REST framework. It would definitively help if you can provide the permissions associated to the view.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM