title: Android post request to django server using HttpUrlConnection gives 403
body: <p>I am learning networking in android using a django server. I am able to make GET requests and get the json response as well as I am able to get the csrf cookie, but when I use the cookie and make a post request , django gives 403 that says csrf verification failed. </p>
  
  <p>I am setting the required header 'X-CSRFToken' with csrf token and also passing the cookies (cookieString) but no success till now.</p>
  
  <p>Here are my classes in android. I am able to make post requests using python-requests library so there is no problem in django server, there is some issue in this android code. Please suggest any way to solve this problem.</p>
  
  <pre><code>private void signupUser() {
      validateData();
      new PostData().execute();
  }
  
  private void validateData() {
      try {
          urlParameters= URLEncoder.encode("code","utf-8")+"="+URLEncoder.encode("100","utf-8");
          urlParameters+= "&amp;"+URLEncoder.encode("username","utf-8")+"="+URLEncoder.encode(username,"utf-8");
          urlParameters+= "&amp;"+URLEncoder.encode("password","utf-8")+"="+URLEncoder.encode(password,"utf-8");
          urlParameters+= "&amp;"+URLEncoder.encode("firstName","utf-8")+"="+URLEncoder.encode(firstName,"utf-8");
          urlParameters+= "&amp;"+URLEncoder.encode("lastName","utf-8")+"="+URLEncoder.encode(lastName,"utf-8");
          urlParameters+= "&amp;"+URLEncoder.encode("email","utf-8")+"="+URLEncoder.encode(email,"utf-8");
      } catch (UnsupportedEncodingException e) {
          e.printStackTrace();
      }
  }
  
  private class PostData extends AsyncTask&lt;Void,Void,String&gt; {
  
      @Override
      protected String doInBackground(Void... params) {
  
          String response="";
  
          try {
  
              // Manage Cookies
              String cookieString="";
              String csrftoken="";
  
  
              cookieManager=io.getCookiesFromURLConnection(urlConnection);
              List&lt;HttpCookie&gt; cookies=cookieManager.getCookieStore().getCookies();
              Iterator&lt;HttpCookie&gt; cookieIterator=cookies.iterator();
              while(cookieIterator.hasNext()){
                  HttpCookie cookie=cookieIterator.next();
                  cookieString+=cookie.getName()+"="+cookie.getValue()+";";
  
                  if(cookie.getName().equals("csrftoken")){
                      csrftoken=cookie.getValue();
                  }
              }
  
  
              url= new URL(Utils.USER_SIGNUP_URL);
              urlConnection=(HttpURLConnection)url.openConnection();
              urlConnection.setRequestMethod("POST");
              urlConnection.setRequestProperty("User-Agent", Utils.USER_AGENT);
              urlConnection.setRequestProperty("Connection", Utils.KEEP_ALIVE);
              urlConnection.setDoOutput(true);
              urlConnection.setDoInput(true);
  
              urlConnection.setRequestProperty("X-CSRFToken", csrftoken);
              urlConnection.setRequestProperty("Cookies", cookieString);
  
              OutputStreamWriter streamWriter=new OutputStreamWriter(urlConnection.getOutputStream());
  
              streamWriter.write(urlParameters);
              streamWriter.flush();
              streamWriter.close();
              int responseCode=urlConnection.getResponseCode();
              response=io.readStream(urlConnection);
  
          } catch (FileNotFoundException ex){
              ex.printStackTrace();
              try {
                  response=io.readErrorStream(urlConnection);
              } catch (IOException e) {
                  e.printStackTrace();
              }
  
          } catch (IOException e) {
              e.printStackTrace();
          }
          return response;
      }
  }
  
  private class GetData extends AsyncTask&lt;Void,Void,String&gt; {
  
      @Override
      protected String doInBackground(Void... params) {
          if(checkConnection()){
              try {
                  return fetchData();
              } catch (IOException e) {
                  e.printStackTrace();
              }
              return null;
          }else{
              Toast.makeText(SignUpActivity.this, "Please connect to internet", Toast.LENGTH_LONG).show();
          }
          return "";
      }
  
      @Override
      protected void onPostExecute(String s) {
          if(s==null){
              return ;
          }
          super.onPostExecute(s);
          signupButton.setEnabled(true);
      }
  
  }
  
  private boolean checkConnection() {
      ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
      NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
      String result = "";
      if (networkInfo != null &amp;&amp; networkInfo.isConnected()) {
          return true;
      }
      return false;
  }
  
  public  String fetchData() throws IOException {
  
      String result="";
  
      try {
          url= new URL(Utils.USER_SIGNUP_URL);
          urlConnection=(HttpURLConnection)url.openConnection();
          result=io.readStream(urlConnection);
          cookieManager=io.getCookiesFromURLConnection(urlConnection);
      } catch (MalformedURLException e) {
          e.printStackTrace();
      }
  
      return result;
  
  }
  
  }
  </code></pre>
  
  <p>Here is the io class:
      public class io {</p>
  
  <pre><code>public static CookieManager getCookiesFromURLConnection(HttpURLConnection urlConnection){
      Map&lt;String,List&lt;String &gt;&gt; headers= urlConnection.getHeaderFields();
      CookieManager cookieManager=new CookieManager();
      List&lt;String&gt; cookiesHeader=headers.get("Set-Cookie");
  
      if(cookiesHeader!=null){
          for(String cookie: cookiesHeader){
              cookieManager.getCookieStore().add(null, HttpCookie.parse(cookie).get(0));
          }
      }
  
      return cookieManager;
  }
  
  }
  </code></pre>
  
  <p>Android Logcat:</p>
  
  <pre><code>09-19 20:55:37.479  17085-17734/kam.app.learnnetworking W/System.err﹕ java.io.FileNotFoundException: http://&lt;website-ip-address&gt;/api/user-login/
  09-19 20:55:37.484  17085-17734/kam.app.learnnetworking W/System.err﹕ at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:206)
  09-19 20:55:37.484  17085-17734/kam.app.learnnetworking W/System.err﹕ at kam.app.learnnetworking.networking.io.readStream(io.java:28)
  09-19 20:55:37.484  17085-17734/kam.app.learnnetworking W/System.err﹕ at kam.app.learnnetworking.activities.SignUpActivity$PostData.doInBackground(SignUpActivity.java:172)
  09-19 20:55:37.484  17085-17734/kam.app.learnnetworking W/System.err﹕ at kam.app.learnnetworking.activities.SignUpActivity$PostData.doInBackground(SignUpActivity.java:123)
  09-19 20:55:37.484  17085-17734/kam.app.learnnetworking W/System.err﹕ at android.os.AsyncTask$2.call(AsyncTask.java:292)
  09-19 20:55:37.484  17085-17734/kam.app.learnnetworking W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:237)
  09-19 20:55:37.484  17085-17734/kam.app.learnnetworking W/System.err﹕ at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
  09-19 20:55:37.484  17085-17734/kam.app.learnnetworking W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
  09-19 20:55:37.484  17085-17734/kam.app.learnnetworking W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
  09-19 20:55:37.484  17085-17734/kam.app.learnnetworking W/System.err﹕ at java.lang.Thread.run(Thread.java:818)
  </code></pre>
  
  <p>Is there any way I can get the sent request and print in android logs? I am new to android networking so don't have much idea.</p>