要修改HttpUrlConnection的标头,请遵循以下步骤:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public static void main(String[] args) throws Exception {
URL url = new URL("https://api.example.com/data");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("User-Agent", "Mozilla/5.0");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Authorization", "Bearer YOUR_ACCESS_TOKEN");
connection.setRequestProperty("Custom-Header", "custom_value");
int responseCode = connection.getResponseCode();
System.out.println("Response Code: " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
}
在上述示例中,我们设置了以下标头:
请注意,您需要将“YOUR_ACCESS_TOKEN”替换为实际的访问令牌。
这是一个使用HttpUrlConnection修改标头的简单示例。根据您的需求,您可能需要根据实际情况调整代码。
大匠光临
实战低代码公开课直播专栏
技术创作101训练营
Techo Day
腾讯技术创作特训营第二季第2期
DB-TALK 技术分享会
腾讯位置服务技术沙龙
云+社区开发者大会(苏州站)
领取专属 10元无门槛券
手把手带您无忧上云