使用OkHttpClient首先需要导入依赖
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.4.1</version>
</dependency>
接下来展示发起请求代码部分。
GET请求
/**
* 地址逆解析
* @param mapStr
* @return
* @throws IOException
*/
public String run(String mapStr) throws IOException {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(mapStr)
.build();
try (Response response = client.newCall(request).execute()) {
System.out.println(response);
String res = response.body().string();
JSONObject pa=JSONObject.parseObject(res);
JSONObject pas= JSONObject.parseObject(pa.getString("result"));
System.out.println("ressponse.body:"+res);
}catch (Exception e){
e.printStackTrace();
System.out.println("地理位置逆解析错误!");
}
return "";
}
POST请求
/**
* 返回剩余流量
* @param iccId
* @return
*/
public Double returnLeftFlow(String iccId){
try{
//发送查询请求
String ip = "http://127.0.0.1:8801";
String interfaceUrl = "/api/v1/card/base/flow/left/{"+ iccId +"}";
Long now = System.currentTimeMillis();
String appId = "test";
String appKey = "test";
//生成签名-sha1Hex
String signBefore = interfaceUrl + now + appId + appKey;
String signAfter = DigestUtils.sha1Hex(signBefore);
//请求路径
String url = ip + interfaceUrl;
//设置请求参数
JSONObject paramObject = new JSONObject();
paramObject.put("test", "test");
//发送请求
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
//这里必须手动设置为json内容类型
.addHeader("appid", appId)
.addHeader("sign", signAfter)
.addHeader("timestamp", now+"")
.addHeader("content-type", "application/json")
//参数放到链接后面
.url(url)
//.post(okhttp3.RequestBody.create(MediaType.parse("application/json; charset=utf-8"), paramObject.toString()))
.build();
Response response = client.newCall(request).execute();
System.out.println(response);
String res = response.body().string();
System.out.println(res);
}catch (Exception e){
e.printStackTrace();
}
return 0.0;
}
注:OkHttpClient可设置请求超时时间,放在静态代码块里边,防止重复加载
static {
httpClient = new OkHttpClient.Builder()
//设置连接超时时间
.connectTimeout(30, TimeUnit.SECONDS)
//设置读取超时时间
.readTimeout(30, TimeUnit.SECONDS)
.build();
}
还可以发送异步http请求,有需要可自行百度。