ScraperAPI helps you control and manage your costs efficiently. By using the max_cost
parameter with your requests, you instruct the API to set a limit on the maximum API credits you'd like to spend per each individual scrape. This helps prevent overspending, ensuring you stay within your individual project's budget.
Copy try {
String apiKey = "API_KEY" ;
String url = "https://api.scraperapi.com?api_key=" + apiKey + "&premium=true&max_cost=5&url=https://example.com/" ;
URL urlForGetRequest = new URL(url) ;
String readLine = null ;
HttpURLConnection connection = (HttpURLConnection) urlForGetRequest . openConnection ();
connection . setRequestMethod ( "GET" );
int responseCode = connection . getResponseCode ();
System . out . println ( "HTTP Response Code: " + responseCode);
if (responseCode == HttpURLConnection . HTTP_OK ) {
BufferedReader in = new BufferedReader( new InputStreamReader( connection . getInputStream())) ;
StringBuffer response = new StringBuffer() ;
while ((readLine = in . readLine ()) != null ) {
response . append (readLine);
}
in . close ();
} else {
throw new Exception( "Error in API Call" ) ;
}
} catch ( Exception ex) {
ex . printStackTrace ();
}
}
}
Copy try {
URL asyncApiUrl = new URL( "https://async.scraperapi.com/jobs" ) ;
HttpURLConnection connection = (HttpURLConnection) asyncApiUrl . openConnection ();
connection . setRequestMethod ( "POST" );
connection . setRequestProperty ( "Content-Type" , "application/json" );
connection . setDoOutput ( true );
String jsonPayload = "{"
+ "\"apiKey\": \"API_KEY\","
+ "\"url\": \"https://example.com\","
+ "\"apiParams\": {"
+ "\"premium\": \"true\","
+ "\"max_cost\": 5"
+ "}"
+ "}" ;
try ( OutputStream outputStream = connection . getOutputStream ()) {
outputStream . write ( jsonPayload . getBytes ( StandardCharsets . UTF_8 ));
outputStream . flush ();
}
int responseCode = connection . getResponseCode ();
System . out . println ( "HTTP Response Code: " + responseCode);
if (responseCode == HttpURLConnection . HTTP_OK ) {
try ( BufferedReader in = new BufferedReader( new InputStreamReader( connection . getInputStream())) ) {
String readLine = null ;
StringBuilder response = new StringBuilder() ;
while ((readLine = in . readLine ()) != null ) {
response . append (readLine);
}
System . out . println ( "Response from server: " + response . toString ());
}
} else {
System . out . println ( "HTTP Error Code: " + responseCode);
throw new Exception( "Error in API Call" ) ;
}
} catch ( Exception ex) {
ex . printStackTrace ();
}
}
}