Tuesday, September 29, 2015

OkHttp - handy HTTP client for Java

One of my friends who is Java engineer suggested me to use this library. I really liked it, it allows you to implement your HTTP calls smoothly and without extra code :)

Find some examples of usage below (two first are taken from their documentation).

GET request: 
 OkHttpClient client = new OkHttpClient();  
 String run(String url) throws IOException {  
  Request request = new Request.Builder()  
    .url(url)  
    .build();  
  Response response = client.newCall(request).execute();  
  return response.body().string();  
 }  

POST request:
 public static final MediaType JSON  
   = MediaType.parse("application/json; charset=utf-8");  
 OkHttpClient client = new OkHttpClient();  
 String post(String url, String json) throws IOException {  
  RequestBody body = RequestBody.create(JSON, json);  
  Request request = new Request.Builder()  
    .url(url)  
    .post(body)  
    .build();  
  Response response = client.newCall(request).execute();  
  return response.body().string();  
 }  

This is my implementation of methods for HTTP calls.
 private JSONObject request(String path, String method, String body) throws ApiException {  
     Builder builder = new Request.Builder()  
       .url(baseUrl + path.replaceAll("^/", ""));  
     if (method.equals("POST")) {  
       builder.post(RequestBody.create(JSON, body));  
     }  
     else if (method.equals("DELETE")) {  
       builder.delete();  
     }  
     try {  
       Response httpResponse = httpClient.newCall(builder.build()).execute();  
       if (httpResponse.code() != 200) {  
         throw new ApiException(httpResponse.body().string());  
       }  
       String httpResponseBody = httpResponse.body().string();  
       System.out.println("ApiClient.request(" + path + "): " + httpResponseBody);  
       return (JSONObject)JSONValue.parse(httpResponseBody);  
     }  
     catch (IOException e) {  
       throw new ApiException(e.getMessage());  
     }  
   }  
   public JSONObject get(String resource, Map<String, String> params) throws ApiException {  
     return request(resource + "?" + urlEncodeUTF8(params), "GET", "");  
   }  
   public JSONObject post(String path, String body) throws ApiException {  
     return request(path, "POST", body);  
   }  

7 comments:

  1. Hello there, my name is Leeroy and I can confirm that your handy HTTP client for Java works great. Thanks for this useful knowledge, and if you dont mind I would like to share with you this service where u can found articles about Java on any taste, for example recently I read one about how to parse json in java https://explainjava.com/parse-json-java/ and it was very interesting and useful for me.

    ReplyDelete
  2. I want to say thanks to you. I have bookmark your site for future updates.
    data science training

    ReplyDelete
  3. I am very blessed to find that code which i was searching for past 2 days basically i help students to find top essay writers Uk which is my part time job but really happy that my problem has been resolved from you provided code.

    ReplyDelete
  4. I have been searching for a handy HTTP client for Java, and I must say that it has greatly helped in integrating merchant cash advance service into my applications. It provides a seamless way to communicate with APIs and ensures smooth transaction processing. Highly recommended for developers in the financial services industry.

    ReplyDelete

  5. There is an error in the below code!

    public static final MediaType JSON
    = MediaType.parse("application/json; charset=utf-8");
    OkHttpClient client = new OkHttpClient();
    String post(String url, String json) throws IOException {
    RequestBody body = RequestBody.create(JSON, json);


    This code is for a Lip Fillers Dubai website

    ReplyDelete
  6. "We will examine some of the well-known data science programmes offered in Pune that guarantee job placement for
    graduates."

    data science course in pune

    ReplyDelete
  7. embroidery digitizing services said...
    OkHttp is undoubtedly a game-changer in the realm of Java-based HTTP clients. Its seamless integration, performance optimization, and user-friendly features make it the go-to choice for developers seeking efficient and reliable HTTP requests. Whether you're dealing with RESTful APIs or simply making network calls, OkHttp simplifies the process, offering a robust and elegant solution. Its flexibility and speed underscore its status as a standout tool in the developer's arsenal, enhancing the overall Java programming experience.

    ReplyDelete