dependencies {
implementation 'com.squareup.okhttp3:okhttp:3.14.9'
}
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.RequestBody;
import okhttp3.MediaType;
public class HttpClient {
private OkHttpClient client;
public HttpClient() {
client = new OkHttpClient();
}
public String sendGetRequest(String url) throws IOException {
Request request = new Request.Builder()
.url(url)
.build();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
public String sendPostRequest(String url, String json) throws IOException {
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
try (Response response = client.newCall(request).execute()) {
return response.body().string();
}
}
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
HttpClient httpClient = new HttpClient();
try {
String response = httpClient.sendGetRequest("http://example.com/api/data");
Log.d("HTTP Response", response);
} catch (IOException e) {
e.printStackTrace();
}
try {
String response = httpClient.sendPostRequest("http://example.com/api/data", "{\"name\":\"John\", \"age\":30}");
Log.d("HTTP Response", response);
} catch (IOException e) {
e.printStackTrace();
}
}
}