JAVA请求第三方API,提示:Server returned HTTP response code: 403 for URL

发布于:2024-04-14 ⋅ 阅读:(51) ⋅ 点赞:(0)

         尝试一下:connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); 

代码示例:

public class HttpPostExample {
    public static void main(String[] args) {
        HttpURLConnection connection = null;
        BufferedReader reader = null;

        try {
            // 创建URL对象
            URL url = new URL("https://api.example.com/resource");

            // 打开连接
            connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法为POST
            connection.setRequestMethod("POST");
            
            //加一行这代码!!!
            connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

            // 设置请求头
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Accept", "application/json");

            // 设置是否向服务器输出数据,默认为false(仅请求)
            connection.setDoOutput(true);

            // 创建请求体数据
            String postData = "{\"key\": \"value\"}";

            // 获取输出流,并写入请求体数据
            try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) {
                byte[] postDataBytes = postData.getBytes(StandardCharsets.UTF_8);
                outputStream.write(postDataBytes);
            }

            // 获取响应
            reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            StringBuilder response = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }

            // 打印响应内容
            System.out.println(response.toString());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭连接和输入流
            if (connection != null) {
                connection.disconnect();
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

  


网站公告

今日签到

点亮在社区的每一天
去签到