16 Şubat 2023 Perşembe

OKHttp

Maven
Şu satırı dahil ederiz
<dependency>
  <groupId>com.squareup.okhttp3</groupId>
  <artifactId>okhttp</artifactId>
  <version>4.9.1</version>
</dependency>
Cancel
Açıklaması şöyle
Both the synchronous and asynchronous versions of sending a request using OkHttp work similarly as described above. In case of an asynchronous request, we get a Future-like value, which can be canceled. In the synchronous case, the thread running the request can be interrupted.

However, when interrupting an OkHttp request, the thread’s interrupted flag remains set. Hence, any subsequent blocking operation (e.g., in a finally block) will immediately throw an InterruptedException, which might not be the desired outcome.

OkHttpClient.Builder Sınıfı
addInterceptor metodu
Örnek
Şöyle yaparız
new OkHttpClient.Builder()
  .addInterceptor(new HttpLoggingInterceptor()
                        .setLevel(HttpLoggingInterceptor.Level.BASIC));
connectionPool metodu
Açıklaması şöyle
OkHttp offers a ConnectionPool capability. When the ConnectionPool option is used, a connection is set up for a limited time period and then sets up a new one, repeatedly, 
Şöyle yaparız
import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;

int MAX_IDLE_CONNECTION = 2;
int KEEP_ALIVE_DURATION = 100;

OkHttpClient client = ...;
var pooledClient = client.newBuilder()
  .connectionPool(new ConnectionPool(MAX_IDLE_CONNECTIONS, 
                                     KEEP_ALIVE_DURATION, 
                                     TimeUnit.MILLISECONDS)
)
followRedirects metodu
Örnek
Şöyle yaparız
OkHttpClient client = new OkHttpClient().newBuilder()
  .followRedirects(false)
  .build();
readTimeout metodu
Örnek
Şöyle yaparız
OkHttpClient client = new OkHttpClient.Builder()
  .readTimeout(1, TimeUnit.SECONDS)
  .build();
OkHttpClient Sınıfı
OkHttpClient sınıfı Builder kullanılarak veya new() çağrısı ile yaratılabilir. HTTP çağrısı için senkron veya asenkron yöntem kullanılır
Şöyle yaparız
Request request = ...

// Blocking
Response response = client.newCall(request).execute();

// Non-Blocking
client.newCall(request).enqueue(new Callback() {...});
newCall metodu
Request.Builder() ile bir okhttp3.Request nesnesi yaratılır.  
client.newCall(request).execute() çağrısı ile bir okhttp3.Response nesnesi alınır

Örnek - JSON
Şöyle yaparız. Burada JSON string GSON ile Java nesnesin çevriliyor.
String API_URL = ...

OkHttpClient client = new OkHttpClient();

String prompt = "My name is";
String apiKey = "YOUR_API_KEY";

MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{\"prompt\": \"" + prompt + "\"}");

Request request = new Request.Builder()
  .url(API_URL)
  .post(body)
  .addHeader("Authorization", "Bearer " + apiKey)
  .addHeader("Content-Type", "application/json")
  .build();

Response response = client.newCall(request).execute();
String responseBody = response.body().string();
Gson gson = new Gson();
ChatGPTResponse response = gson.fromJson(responseBody, ChatGPTResponse.class);
Örnek - JSON
Şöyle yaparız. Burada JSON string JSON-Java ile Java nesnesine çevriliyor.
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.json.JSONArray;
import org.json.JSONObject;

@Service
public class GeocodingService {

  private final OkHttpClient httpClient = new OkHttpClient();

  public JSONObject search(String query) throws IOException {
    Request request = new Request.Builder()
      .url("https://nominatim.openstreetmap.org/search?format=json&q=" + query)
      .build();

    try(Response response = httpClient.newCall(request).execute()) {
      if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

      JSONArray jsonArray = new JSONArray(response.body().string());

      if(jsonArray.length() > 0) {
        return jsonArray.getJSONObject(0);
      }
      return null;
    }
  }
}
Örnek - Callback
Şöyle yaparız
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

OkHttpClient client = new OkHttpClient();

Request request = new Request.Builder()
  .url("https://jsonplaceholder.typicode.com/todos/1")
  .build();

client.newCall(request).enqueue(new Callback() {
  @Override
  public void onFailure(Call call, IOException e) {
    e.printStackTrace();
  }
  @Override
  public void onResponse(Call call, Response response) throws IOException {
    if (!response.isSuccessful()) {
      throw new IOException("Unexpected code " + response);
    }
    String responseBody = response.body().string();
    System.out.println(responseBody);
  }
});
MockWebServer Sınıfı
Test için kullanılır
url metodu
Örnek
Şöyle yaparız
class InventoryClientTest {

  private InventoryClient cut;

  public static MockWebServer mockBackEnd;

  @BeforeAll
  public static void setUp() throws IOException {
    mockBackEnd = new MockWebServer();
    mockBackEnd.start();
  }

  @AfterAll
  public static void tearDown() throws IOException {
    mockBackEnd.shutdown();
  }

  @BeforeEach
  public void before() {
      cut = new InventoryClient(new InventoryClientProperties()
        .setUrl(mockBackEnd.url("/").toString())
        .setRetry(new RetryBackoffProperties()
                   .setMaxAttempts(2)
                        .setBackoffDuration(Duration.ofMillis(10000))));
    }
    ...
}
test şöyledir
@Test
public void verifyGetByNameReturnsEntryForSuccessfulRequestUsingBlock() {
  InventoryEntry expectedEntry = new InventoryEntry(42, "...", 5);

  mockBackEnd.enqueue(assembleResponse(expectedEntry));

  InventoryEntry entry = cut
    .getByName(expectedEntry.name())
    .block();

  assertThat(entry).isEqualTo(expectedEntry);
}


Hiç yorum yok:

Yorum Gönder