OKHttp使用筆記

GitHub說明https://square.github.io/okhttp/

基於socket的java項目,須要對進行文件流操做,數據量較爲巨大 

  • boot中導入pom依賴

     <!--okhttp3-->
            <dependency>
                <groupId>com.squareup.okhttp3</groupId>
                <artifactId>okhttp</artifactId>
                <version>3.13.1</version>
            </dependency>

 

  • 編寫工具類

    import okhttp3.*;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.util.CollectionUtils;
    
    import java.io.IOException;
    import java.util.Map;
    import java.util.Objects;
    
    /**
     * 利用OKHttp進行get和post的訪問
     *
     */
    public class OKHttpUtil {
    
       static final Logger logger = LoggerFactory.getLogger(OKHttpUtil.class);
        /**
         * 發起get請求
         *
         * @param url
         * @return
         */
        public static String httpGet(String url) {
            String result = null;
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder().url(url).build();
            try {
                Response response = client.newCall(request).execute();
                result = response.body().string();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return result;
        }
    
        /**
         * 執行同步 Post請求
         * @param url
         * @param jsonStr
         * @param headers
         * @return
         * @throws IOException
         */
        public static Response httpPost(String url, String jsonStr, Map<String, String> headers) throws IOException {
            //構造請求體
            RequestBody requestBody = RequestBody.create(MediaType.parse("text/html;charset=utf-8"), jsonStr);
            //建立requestBody
            Request.Builder requestBuilder = new Request.Builder().url(url).post(requestBody);
            //構造請求頭
            if(!CollectionUtils.isEmpty(headers)){
                for (Map.Entry<String, String> mapEntry : headers.entrySet()) {
                    // value不爲空
                    if(!Objects.isNull(mapEntry.getValue())){
                        requestBuilder.addHeader(mapEntry.getKey(), String.valueOf(mapEntry.getValue()));
                    }
                }
            }
            //構建請求
            Request request = requestBuilder.build();
            //獲取client
            OkHttpClient okHttpClient = new OkHttpClient();
            //執行
            Response response = okHttpClient.newCall(request).execute();
            return response;
        }
    
    
    }
相關文章
相關標籤/搜索