Advertisement
Wolverine_X-Man

Untitled

May 13th, 2023
902
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 1.81 KB | Source Code | 0 0
  1. import java.net.HttpURLConnection;
  2. import java.net.URL;
  3.  
  4. public class MainActivity extends AppCompatActivity {
  5.     @Override
  6.     protected void onCreate(Bundle savedInstanceState) {
  7.         super.onCreate(savedInstanceState);
  8.         setContentView(R.layout.activity_main);
  9.  
  10.         new Thread(new Runnable() {
  11.             @Override
  12.             public void run() {
  13.                 try {
  14.                     URL url = new URL("http://www.example.com/api");
  15.                     HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
  16.                     httpConn.setRequestMethod("GET");
  17.                     int responseCode = httpConn.getResponseCode();
  18.                     if (responseCode == HttpURLConnection.HTTP_OK) {
  19.                         // Do something with the response
  20.                     } else {
  21.                         // Handle error
  22.                     }
  23.                 } catch (Exception e) {
  24.                     e.printStackTrace();
  25.                 }
  26.             }
  27.         }).start();
  28.     }
  29. }
  30.  
  31.  
  32.  
  33.  
  34.  
  35. import com.google.gson.Gson;
  36.  
  37. // Define a model class
  38. class MyModel {
  39.     String field1;
  40.     int field2;
  41.     // ...
  42. }
  43.  
  44. // In your API call code
  45. if (responseCode == HttpURLConnection.HTTP_OK) {
  46.     // Get the response body as a string
  47.     InputStream in = httpConn.getInputStream();
  48.     BufferedReader reader = new BufferedReader(new InputStreamReader(in));
  49.     StringBuilder response = new StringBuilder();
  50.     String line;
  51.     while ((line = reader.readLine()) != null) {
  52.         response.append(line);
  53.     }
  54.     reader.close();
  55.  
  56.     // Convert the response string into a model object
  57.     Gson gson = new Gson();
  58.     MyModel model = gson.fromJson(response.toString(), MyModel.class);
  59.  
  60.     // Do something with the model object
  61. } else {
  62.     // Handle error
  63. }
  64.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement