Setting custom header using HttpURLConnection

前端 未结 2 1266
难免孤独
难免孤独 2021-02-14 06:57

I am simply making a GET request to a Rest API using HttpURLConnection.

I need to add some custom headers but I am getting null wh

相关标签:
2条回答
  • 2021-02-14 07:26

    It is a good idea to send

    conn.setRequestProperty("Content-Type", "application/json");
    conn.setRequestProperty("CustomHeader", token);
    

    instead of

    // Set Headers
    conn.setRequestProperty("CustomHeader", "someValue");
    conn.setRequestProperty("accept", "application/json");
    

    Both the type value and header should be changed. it works in my case.

    0 讨论(0)
  • 2021-02-14 07:35

    The conn.getHeaderField("CustomHeader") returns the response header not the request one.

    To return the request header use: conn.getRequestProperty("CustomHeader")

    0 讨论(0)
提交回复
热议问题