Api Java Spring
Пытаюсь получить с этого сайта ответ https://some-random-api.ml/facts/dog Должен приходить джейсон, но приходит 403 статусный код, не понимаю, в чем ошибка
@GetMapping("/shelter")
public String getShelterPage(Authentication authentication, Model model){
if(authentication != null){
String a = getJSON("https://some-random-api.ml/facts/dog");
String fact = null;
if (a != null) {
fact = a.substring(9,a.length()-3);
}
model.addAttribute("authentication", authentication);
model.addAttribute("fact",fact);
System.out.println(a);
}
return "shelter";
}
public static String getJSON(String urle) {
try {
URL url = new URL(urle);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Content-length", "0");
con.setConnectTimeout(30000);
con.connect();
int resp = con.getResponseCode();
System.out.println(resp);
if(resp == 200) {
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line);
sb.append("\n");
}
br.close();
return sb.toString();
} else {
/*Log.e("RESP", "Ответ сервера: " + resp);*/
}
} catch(Exception e) { e.printStackTrace(); }
return null;
}
}
freemarker.core.InvalidReferenceException: The following has evaluated to null or missing: ==> fact [in template "shelter.ftlh" at line 20, column 22]
Tip: If the failing expression is known to legally refer to something that's sometimes null or missing, either specify a default value like myOptionalVar!myDefault, or use <#if myOptionalVar??>when-present<#else>when-missing. (These only cover the last step of the expression; to cover the whole expression, use parenthesis: (myOptionalVar.foo)!myDefault, (myOptionalVar.foo)??
FTL stack trace ("~" means nesting-related):
- Failed at: ${fact} [in template "shelter.ftlh" at line 20, column 20]
Ответы (1 шт):
Автор решения: Дмитрий
→ Ссылка
Все потому, что вы не установили юзер агента. Добавьте эту строку и все заработает
con.setRequestProperty("User-Agent", "Mozilla/5.0");
Вот код для того, чтобы проверить, что 403 действительно нет без спринга и прочих зависимостей:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class Test {
public static void main(String[] args) {
getShelterPage();
}
//@GetMapping("/shelter")
public static String getShelterPage(){//(Authentication authentication, Model model) {
//if (authentication != null) {
String a = getJSON("https://some-random-api.ml/facts/dog");
String fact = null;
if (a != null) {
fact = a.substring(9, a.length() - 3);
}
//model.addAttribute("authentication", authentication);
//model.addAttribute("fact", fact);
System.out.println(a);
//}
return "shelter";
}
public static String getJSON(String urle) {
try {
URL url = new URL(urle);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Content-length", "0");
con.setRequestProperty("User-Agent", "Mozilla/5.0");
con.setConnectTimeout(30000);
con.connect();
int resp = con.getResponseCode();
System.out.println(resp);
if (resp == 200) {
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line);
sb.append("\n");
}
br.close();
return sb.toString();
} else {
/*Log.e("RESP", "Ответ сервера: " + resp);*/
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}