2020import com .vwo .packages .network_layer .models .RequestModel ;
2121import com .vwo .packages .network_layer .models .ResponseModel ;
2222
23+ import java .io .BufferedInputStream ;
2324import java .io .BufferedReader ;
25+ import java .io .ByteArrayInputStream ;
26+ import java .io .IOException ;
27+ import java .io .InputStream ;
2428import java .io .InputStreamReader ;
2529import java .io .OutputStream ;
2630import java .net .HttpURLConnection ;
2933import java .util .HashMap ;
3034import java .util .LinkedHashMap ;
3135import java .util .Map ;
36+ import java .util .zip .GZIPInputStream ;
3237
3338public class NetworkClient implements NetworkClientInterface {
3439
@@ -41,6 +46,40 @@ public static String constructUrl(Map<String, Object> networkOptions) {
4146 return networkOptions .get ("scheme" ).toString ().toLowerCase () + "://" + hostname + path ;
4247 }
4348
49+ /**
50+ * Magic Number Detection - Check first two bytes for gzip signature (0x1f, 0x8b)
51+ * This is the most reliable method as it checks the actual content
52+ */
53+ private boolean isGzippedByMagicNumber (InputStream inputStream ) throws IOException {
54+ if (!inputStream .markSupported ()) {
55+ return false ;
56+ }
57+
58+ inputStream .mark (2 );
59+ int byte1 = inputStream .read ();
60+ int byte2 = inputStream .read ();
61+ inputStream .reset ();
62+
63+ return (byte1 == 0x1f && byte2 == 0x8b );
64+ }
65+
66+ /**
67+ * This method is used to get the input stream from the connection
68+ * @param connection The HttpURLConnection object
69+ * @return The InputStream object
70+ * @throws IOException If an I/O error occurs
71+ */
72+ private InputStream getInputStream (HttpURLConnection connection ) throws IOException {
73+ InputStream rawInputStream = connection .getInputStream ();
74+
75+ BufferedInputStream bufferedStream = new BufferedInputStream (rawInputStream );
76+ if (isGzippedByMagicNumber (bufferedStream )) {
77+ return new GZIPInputStream (bufferedStream );
78+ }
79+
80+ return bufferedStream ;
81+ }
82+
4483 /**
4584 * Performs a GET request using the provided RequestModel.
4685 * @param requestModel The model containing request options.
@@ -71,7 +110,12 @@ public ResponseModel GET(RequestModel requestModel){
71110 return responseModel ;
72111 }
73112
74- BufferedReader in = new BufferedReader (new InputStreamReader (connection .getInputStream ()));
113+ // Use the comprehensive gzip detection method
114+ InputStream inputStream = getInputStream (connection );
115+ if (inputStream instanceof GZIPInputStream ) {
116+ responseModel .setIsGzipped (true );
117+ }
118+ BufferedReader in = new BufferedReader (new InputStreamReader (inputStream , StandardCharsets .UTF_8 ));
75119 String inputLine ;
76120 StringBuilder response = new StringBuilder ();
77121
0 commit comments