本文主要是介绍JAVA请求第三方API,提示:Server returned HTTP response code: 403 for URL,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
尝试一下: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();// 设置请求方法为POSTconnection.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();}}}}
}
这篇关于JAVA请求第三方API,提示:Server returned HTTP response code: 403 for URL的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!