当用postman和浏览器访问的时候,能够正常获取数据,在代码调用接口的时候出现403和404错误。
一、出现问题的原因
根据访问的网站的管理员的提示,对访问的参数进行调整,模拟浏览器访问。
二、模拟浏览器访问
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class holidayTest {
public static void main(String[] args) {
String methodUrl = "http://timor.tech/api/holiday/year/2021/";
HttpURLConnection connection = null;
BufferedReader reader = null;
String line = null;
try {
URL url = new URL(methodUrl);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("User-Agent", "PostmanRuntime/7.26.8");
connection.connect();
int type = connection.getResponseCode();
if (type == HttpURLConnection.HTTP_OK) {
reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
StringBuilder result = new StringBuilder();
while ((line = reader.readLine()) != null) {
result.append(line).append(System.getProperty("line.separator"));
}
System.out.println(result.toString());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
connection.disconnect();
}
}
}
三、以下代码出现:403
以下代码需要模拟浏览器的访问才能解决问题。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class holidayTest {
public static void main(String[] args) {
String methodUrl = "http://timor.tech/api/holiday/year/2021/";
HttpURLConnection connection = null;
BufferedReader reader = null;
String line = null;
try {
URL url = new URL(methodUrl);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
int type = connection.getResponseCode();
if (type == HttpURLConnection.HTTP_OK) {
reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
StringBuilder result = new StringBuilder();
while ((line = reader.readLine()) != null) {
result.append(line).append(System.getProperty("line.separator"));
}
System.out.println(result.toString());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
connection.disconnect();
}
}
}
参考资料
【免费的节假日API】http://timor.tech/api/holiday 【模拟浏览器请求访问】https://www.cnblogs.com/wyw-action/articles/6682620.html
|