HttpURLConnection
java
2 months ago
3.7 kB
4
Indexable
Never
import java.net.HttpURLConnection; import java.net.URL; import java.io.OutputStream; public class GraphQLQueryNative { private static final String ENDPOINT_URL = "https://streaming.bitquery.io/graphql"; private static final String API_KEY = "*****" //API KEY public static void main(String[] args) { try { String responseBody = executeQuery(); System.out.println(responseBody); } catch (Exception e) { e.printStackTrace(); } } private static String executeQuery() throws Exception { URL url = new URL(ENDPOINT_URL); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "application/json"); conn.setRequestProperty("X-API-KEY", API_KEY); conn.setDoOutput(true); String query = "subscription NotAlwaysWorkingSub {" + "EVM(network: eth, trigger_on: head) {" + "buyside: DEXTrades(" + "orderBy: {descending: Block_Time}," + "where: {" + "Trade: {" + "Sell: {" + "Currency: {" + "SmartContract: {is: \\\"0x423f4e6138E475D85CF7Ea071AC92097Ed631eea\\\"}" + "}" + "}," + "Dex: {" + "ProtocolName: {is: \\\"uniswap_v3\\\"}," + "Pair: {SmartContract: {}}" + "}" + "}" + "}" + ") {" + "Block {" + "Number," + "Time" + "}," + "Transaction {" + "From," + "To," + "Hash" + "}," + "Trade {" + "Buy {" + "Amount," + "Buyer," + "Currency {" + "Name," + "Symbol," + "SmartContract" + "}," + "Seller," + "Price" + "}," + "Sell {" + "Amount," + "Buyer," + "Currency {" + "Name," + "SmartContract," + "Symbol" + "}," + "Seller," + "Price" + "}," + "Dex {" + "ProtocolFamily," + "ProtocolName," + "SmartContract," + "Pair {" + "SmartContract" + "}" + "}" + "}" + "}" + "}" + "}"; String payload = "{\"query\":\"" + query + "\",\"variables\":\"{}\"}"; try (OutputStream os = conn.getOutputStream()) { byte[] input = payload.getBytes("utf-8"); os.write(input, 0, input.length); } int responseCode = conn.getResponseCode(); if (responseCode != HttpURLConnection.HTTP_OK) { throw new RuntimeException("Failed : HTTP error code : " + responseCode); } java.io.InputStream is = conn.getInputStream(); java.util.Scanner s = new java.util.Scanner(is).useDelimiter("\\A"); String responseBody = s.hasNext() ? s.next() : ""; conn.disconnect(); return responseBody; } }