1、引入okhttp jar
< dependency>
< groupId> com. squareup. okhttp3< / groupId>
< artifactId> okhttp< / artifactId>
< version> 3.9 .1 < / version>
< / dependency>
2、httpUtil.java
import cn. chinaunicom. paas. dto. TestDto ;
import com. alibaba. fastjson. JSON;
import okhttp3. * ;
import java. io. IOException ;
import java. util. ArrayList ;
import java. util. HashMap ;
import java. util. List ;
import java. util. Map ;
import java. util. concurrent. TimeUnit ;
public class HttpUtil {
private final static Map < String , List < Cookie > > COOKIE_MAP = new HashMap < > ( ) ;
private static final OkHttpClient CLIENT;
static {
CLIENT = new OkHttpClient. Builder ( ) . cookieJar ( new CookieJar ( ) {
@Override
public void saveFromResponse ( HttpUrl url, List < Cookie > cookies) {
COOKIE_MAP. put ( url. host ( ) , cookies) ;
}
@Override
public List < Cookie > loadForRequest ( HttpUrl url) {
List < Cookie > cookies = COOKIE_MAP. get ( url. host ( ) ) ;
return cookies != null ? cookies : new ArrayList < > ( ) ;
}
} )
. connectTimeout ( 60 * 1000L , TimeUnit . MILLISECONDS)
. readTimeout ( 5 * 60 * 1000L , TimeUnit . MILLISECONDS)
. writeTimeout ( 5 * 60 * 1000L , TimeUnit . MILLISECONDS)
. build ( ) ;
}
public static String put ( String req, Headers headers, String url) throws IOException {
RequestBody requestBody = FormBody . create ( okhttp3. MediaType. parse ( org. springframework. http. MediaType. APPLICATION_JSON_UTF8_VALUE) ,
req) ;
Request request = new Request. Builder ( )
. headers ( headers)
. put ( requestBody)
. url ( url)
. build ( ) ;
Response response = CLIENT. newCall ( request) . execute ( ) ;
return JSON. toJSONString ( response. body ( ) ) ;
}
public static String post ( String req, Headers headers, String url) throws IOException {
RequestBody requestBody = FormBody . create ( okhttp3. MediaType. parse ( org. springframework. http. MediaType. APPLICATION_JSON_UTF8_VALUE) ,
req) ;
Request request = new Request. Builder ( )
. headers ( headers)
. put ( requestBody)
. url ( url)
. build ( ) ;
Response response = client. newCall ( request) . execute ( ) ;
return JSON. toJSONString ( response. body ( ) ) ;
}
public static String get ( Headers headers, String url) throws IOException {
Request request = new Request. Builder ( )
. headers ( headers)
. url ( url)
. build ( ) ;
Response response = client. newCall ( request) . execute ( ) ;
return JSON. toJSONString ( response. body ( ) ) ;
}
}
3、httpUtilTest
@Test
public void test3 ( ) throws IOException {
String url = "http://www.xxx.com" ;
String u = "test" ;
String p = "xxx" ;
String value = u + ":" + p;
Map < String , String > paramMap = new HashMap < > ( 1 ) ;
paramMap. put ( "key1" , value) ;
Headers headers = Headers . of ( paramMap) ;
TestUtilDto testUtilDto = TestUtilDto . builder ( ) . value ( 100 ) . build ( ) ;
String result = HttpUtil . put ( JSON. toJSONString ( testUtilDto) , headers, url) ;
System . out. println ( result) ;
}