1.post请求:
import okhttp3.*;
import org.apache.http.client.config.RequestConfig;
import java.util.HashMap;
import java.util.Map;
public class HttpClientTest {
// 编码格式。发送编码格式统一用UTF-8
private static final String ENCODING = "UTF-8";
// 设置连接超时时间,单位毫秒。
private static final int CONNECT_TIMEOUT = 6000;
// 请求获取数据的超时时间(即响应时间),单位毫秒。
private static final int SOCKET_TIMEOUT = 10000;
public static String getResponse(String path,Map<String,String> params) throws Exception {
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(CONNECT_TIMEOUT).setSocketTimeout(SOCKET_TIMEOUT).build();
OkHttpClient client = new OkHttpClient();
MediaType json = MediaType.parse("application/json; charset=utf-8");
RequestBody loginBody =
RequestBody.create(json, com.alibaba.fastjson.JSON.toJSONString(params));
// 创建一个请求
Request request = new Request.Builder()
.url(path)
.post(loginBody)
.addHeader("Content-Type", "application/json")
.build();
//给okhttpClient传入一个请求,这个时候得到一个call
Call call = client.newCall(request);
Response response = call.execute();
int code = response.code();
if (code == 200) {
// System.out.println(response.body().string());
return response.body().string();
}
return "500";
}
}
调用方式:
String response = HttpClientTest.getResponse(loginPath,params);
2. get请求
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import org.apache.http.client.config.RequestConfig;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class HttpClient {
// 编码格式。发送编码格式统一用UTF-8
private static final String ENCODING = "UTF-8";
// 设置连接超时时间,单位毫秒。
private static final int CONNECT_TIMEOUT = 6000;
// 请求获取数据的超时时间(即响应时间),单位毫秒。
private static final int SOCKET_TIMEOUT = 10000;
public static String getResponse(String path) throws Exception {
OkHttpClient client = new OkHttpClient();
//构建一个请求对象
Request request = new Request.Builder().url(path).build();
//发送请求
Response response = client.newCall(request).execute();
//打印服务端传回的数据
System.out.println(response.body().string());
return response.body().string();
}
public static void main(String[] args) {
HashMap<String,String> params = new HashMap<>() ;
params.put("phoneNum","19939003136");
try {
String response = HttpClient.getResponse("http://172.16.20.46:9093/bllweb/usercenter/accmanage/phonetype?phonenum=19939003136");
System.out.println("res------" + response);
JSONObject json = JSONObject.parseObject(response);
System.out.println("----------" + response);
} catch (Exception e) {
e.printStackTrace();
}
}
}