Есть сервис https://baza-otvetov.ru, на котором есть форма викторины https://baza-otvetov.ru/quiz
Сервер отдает на запрос к https://baza-otvetov.ru/quiz страницу html, а после загрузки выполняется следующий javascript-код
<script type="text/javascript">
function ask(){
$.ajax({
cache: false,
type: "POST",
url: "/quiz/ask",
data: {
},
beforeSend: function(){
$(".check").html('<div style="text-align:center;"><img src="/design/images/ajaxloader.gif" /></div>');
},
success: function(html){
$(".check").html(html);
},
error: function(){
$(".check").html('Произошла ошибка, попробуйте обновить страницу.');
}
});
}
$(document).ready(function () {
ask();
});
</script>
Т.е. вопрос с ответами он подгружает POST-запросом к https://baza-otvetov.ru/quiz/ask. Так вот, я никак не могу сэмулировать этот ПОСТ-запрос.
@SpringBootApplication
public class PostrequestApplication implements CommandLineRunner {
private static final Logger logger = LoggerFactory.getLogger(PostrequestApplication.class);
private static final String USER_AGENT = "Mozilla/5.0";
static final String COOKIES_HEADER = "Set-Cookie";
static java.net.CookieManager msCookieManager = new java.net.CookieManager();
public static void main(String[] args) {
SpringApplication.run(PostrequestApplication.class, args);
}
@Override
public void run(String... strings) throws Exception {
logger.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>> START <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<");
System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
HttpsURLConnection get = sendGet("https://baza-otvetov.ru/quiz");
HttpsURLConnection post = preparePostConnection("https://baza-otvetov.ru/quiz/ask", get);
sendPost(post);
}
private HttpsURLConnection preparePostConnection(String url, HttpsURLConnection get) throws Exception {
System.out.println("\nGET RESPONSE HEADERS");
Map<String, List<String>> map = get.getHeaderFields();
for (Map.Entry<String, List<String>> entry : map.entrySet()) {
System.out.println("Key : " + entry.getKey() + ", Value : " + entry.getValue());
}
System.out.println("POST: "+url);
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
con.setRequestMethod("POST");
//set cookies
Map<String, List<String>> headerFields = get.getHeaderFields();
List<String> cookiesHeader = headerFields.get(COOKIES_HEADER);
if (cookiesHeader != null) {
for (String cookie : cookiesHeader) {
msCookieManager.getCookieStore().add(null, HttpCookie.parse(cookie).get(0));
}
}
if (msCookieManager.getCookieStore().getCookies().size() > 0) {
// While joining the Cookies, use ',' or ';' as needed. Most of the servers are using ';'
con.setRequestProperty("Cookie", join(msCookieManager.getCookieStore().getCookies(), ";"));
}
//add reuqest header
con.setRequestProperty("content-length", "0");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "ru-RU,ru;q=0.9,en-US;q=0.8,en;q=0.7");
//con.setRequestProperty("Access-Control-Allow-Origin", "*");
//con.setRequestProperty("Access-Control-Allow-Credentials", "true");
con.setRequestProperty("origin", "https://baza-otvetov.ru");
con.setRequestProperty("referer", "https://baza-otvetov.ru/quiz");
System.out.println("\nPOST REQUEST HEADERS");
Map<String, List<String>> map_post = con.getHeaderFields();
for (Map.Entry<String, List<String>> entry : map_post.entrySet()) {
System.out.println("Key : " + entry.getKey() + ", Value : " + entry.getValue());
}
return con;
}
private HttpsURLConnection sendGet(String url) throws Exception {
System.out.println("GET: "+url);
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode();
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
return con;
}
private void sendPost(HttpsURLConnection con) throws Exception {
// Send post request
con.setDoOutput(true);
int responseCode = con.getResponseCode();
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println("RESPONSE: "+response.toString());
}
public static String join(List<HttpCookie> var0, String var1) {
StringBuffer var2 = new StringBuffer();
for(Iterator var3 = var0.iterator(); var3.hasNext(); var2.append(var3.next().toString())) {
if (var2.length() != 0) {
var2.append(var1);
}
}
return var2.toString();
}
}
Все равно сервер ничего не возвращает.
Как побороть CORS?