无法使用HttpURLConnection Android发送JWT作为授权标头

时间:2020-04-18 14:28:59

标签: android jwt httpurlconnection

我正在用标头发送JWT的POST请求,我将JWT保存在我的sharedpreference中,如下所示:

StringBuilder sb = new StringBuilder();
       try {
           url = new URL(requestURL);
           HttpURLConnection conn = (HttpURLConnection) url.openConnection();
           conn.setReadTimeout(15000);
           conn.setConnectTimeout(15000);
           conn.setRequestMethod("POST");
           conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
           jwt = user.getJwt() ;
           Log.d("handler", jwt);

           conn.setRequestProperty("My-Auth",  jwt);
           conn.setDoInput(true);
           conn.setDoOutput(true);

问题是当我在其中放置JWT:conn.setRequestProperty("My-Auth", jwt);时,它将不起作用。但是,当我复制硬编码的JWT而不是jwt变量时,它可以工作。像这样:conn.setRequestProperty("My-Auth", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJXaW5rYSIsImF1ZCI6IlRIRV9BVURJRU5DRSIsImlhdCI6MTU4NzIxMjgyNCwibmJmIjoxNTg3MjEyODM0LCJlOjE1ODcyMTg4MjQsImRhdGEiOnsiaWQiOiIyIiwiTmFtZSI6Ik5lc2hhdDIiLCJQaG9uZSI6IjA5MTIwMzIxOTMxIiwiY29pbnMiOiIwIiwicG9pbnRzIjoiNiJ9fQ.rOIGdlcide3RyRmeUSBuym9ULxt04uwuqXIddEZHk7Y")

正如我在Log.d中打印的那样,点是jwt变量具有值。

很明显,我无法在我的代码中使用经过硬编码的JWT,因为它一直在变化。为什么它不起作用?

0 个答案:

没有答案