1. Apache HttpClient:
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
public class HttpClientExample {
public static void main(String[] args) {
HttpClient httpClient = HttpClientBuilder.create().build();
HttpGet httpGet = new HttpGet("http://example.com");
try {
HttpResponse response = httpClient.execute(httpGet);
} catch (IOException e) {
e.printStackTrace();
}
}
}
2. OkHttp:
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import java.io.IOException;
public class OkHttpExample {
public static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
public static void main(String[] args) {
OkHttpClient client = new OkHttpClient();
RequestBody requestBody = RequestBody.create(JSON, "{\"key\": \"value\"}");
Request request = new Request.Builder()
.url("http://example.com")
.post(requestBody)
.build();
try {
Response response = client.newCall(request).execute();
} catch (IOException e) {
e.printStackTrace();
}
}
}
3. Spring RestTemplate:
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
public class RestTemplateExample {
public static void main(String[] args) {
RestTemplate restTemplate = new RestTemplate();
String url = "http://example.com";
String requestJson = "{\"key\": \"value\"}";
HttpEntity<String> requestEntity = new HttpEntity<>(requestJson);
ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.PUT, requestEntity, String.class);
}
}