Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.net.HttpURLConnection;
- import java.net.URL;
- public class MainActivity extends AppCompatActivity {
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- new Thread(new Runnable() {
- @Override
- public void run() {
- try {
- URL url = new URL("http://www.example.com/api");
- HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
- httpConn.setRequestMethod("GET");
- int responseCode = httpConn.getResponseCode();
- if (responseCode == HttpURLConnection.HTTP_OK) {
- // Do something with the response
- } else {
- // Handle error
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }).start();
- }
- }
- import com.google.gson.Gson;
- // Define a model class
- class MyModel {
- String field1;
- int field2;
- // ...
- }
- // In your API call code
- if (responseCode == HttpURLConnection.HTTP_OK) {
- // Get the response body as a string
- InputStream in = httpConn.getInputStream();
- BufferedReader reader = new BufferedReader(new InputStreamReader(in));
- StringBuilder response = new StringBuilder();
- String line;
- while ((line = reader.readLine()) != null) {
- response.append(line);
- }
- reader.close();
- // Convert the response string into a model object
- Gson gson = new Gson();
- MyModel model = gson.fromJson(response.toString(), MyModel.class);
- // Do something with the model object
- } else {
- // Handle error
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement