HttpURLConnection 如何添加header呢?
下文笔者讲述HttpURLConnection添加header的方法及示例分享,如下所示
我们只需将HttpURLConnection中添加setRequestProperty 即可添加相应的header例:HttpURLConnection添加header方法
URL myURL = new URL(serviceURL); HttpURLConnection myURLConnection = (HttpURLConnection)myURL.openConnection(); String userCredentials = "username:password"; String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userCredentials.getBytes())); myURLConnection.setRequestProperty ("Authorization", basicAuth); myURLConnection.setRequestMethod("POST"); myURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); myURLConnection.setRequestProperty("Content-Length", "" + postData.getBytes().length); myURLConnection.setRequestProperty("Content-Language", "en-US"); myURLConnection.setUseCaches(false); myURLConnection.setDoInput(true); myURLConnection.setDoOutput(true);
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。