HTTP Header 中加入 Access Token

Android在網頁上拉取資料時, 有時候會有Access Token的需求
若不加入, 網頁就有可能回傳錯誤

可以利用httpURLConnection.addRequestProperty(“參數名”, “參數”)); 加入Access Token

 

完整Code:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        new Thread(new Runnable() {
            @Override
            public void run() {

                String url = "";  //這邊加入你需要的Header

                String headerKey = "";//參數名
                String headerValue = "";//參數

                //這邊做成hashMap 根據Key(參數名)和Value(參數)加入Header
                HashMap<String, String> additionalHeaderHashMap = new HashMap<>();
                additionalHeaderHashMap.put(headerKey, headerValue);
                runHttp(url, additionalHeaderHashMap);

            }
        }).start();

    }

    private String runHttp(String httpUrl, HashMap additionalHeader) {
        HttpURLConnection httpURLConnection = null;
        try {
            URL url = new URL(httpUrl);
            httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("GET");

            //這邊加入Header
            if (additionalHeader != null) {
                Iterator<Map.Entry<String, String>> iterator = additionalHeader.entrySet().iterator();
                while (iterator.hasNext()) {
                    Map.Entry<String, String> iteratorEntry = iterator.next();
                    httpURLConnection.addRequestProperty(iteratorEntry.getKey(), iteratorEntry.getValue());
                }
            }

            int responseCode = httpURLConnection.getResponseCode();
            if (responseCode == 200) {
                BufferedReader in = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
                String inputLine = "";
                StringBuffer response = new StringBuffer();
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                return response.toString();

            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (httpURLConnection != null)
                httpURLConnection.disconnect();
        }
    }
}

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *