在OkHttpClient的使用中,建议将其定义为静态变量,以便在整个应用程序中共享。以下是使用OkHttpClient进行HTTP GET和POST请求的示例代码:
```java
// 温馨小提示:在使用OkHttpClient时,最好将其定义为静态变量
private static OkHttpClient okHttpClient;
static {
okHttpClient = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.readTimeout(60, TimeUnit.SECONDS)
.build();
}
// HTTP GET请求示例
public String run(String url) throws IOException {
Request request = new Request.Builder().url(url).build();
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
return response.body().string();
} else {
throw new IOException("Unexpected code " + response);
}
}
// HTTP POST提交Json数据示例
public String postJsonData(String url, Map
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), new Gson().toJson(jsonData));
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
return response.body().string();
} else {
throw new IOException("Unexpected code " + response);
}
}
```
以下是重构后的代码:
```java
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;
public class Main {
public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
public static void main(String[] args) {
OkHttpClient client = new OkHttpClient();
String url = "https://api.example.com/post";
String json = "{\"key\":\"value\"}";
try {
String response = post(url, json);
System.out.println(response);
} catch (IOException e) {
e.printStackTrace();
}
}
public static 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();
if (response.isSuccessful()) {
return response.body().string();
} else {
throw new IOException("Unexpected code " + response);
}
}
}
```
以下是重构后的代码:
```java
OkHttpClient client = new OkHttpClient();
public String post(String url, Map
FormBody.Builder formBodyBuilder = new FormBody.Builder();
for (Map.Entry
formBodyBuilder.add(entry.getKey(), entry.getValue());
}
RequestBody requestBody = formBodyBuilder.build();
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
return response.body().string();
} else {
throw new IOException("Unexpected code " + response);
}
}
```
重构的思路是将表单数据从字符串转换为`Map
以下是重构后的代码:
```java
public List
List
List
for (HzsPolyvDetails polyvDetails : polyvDetailsList) {
StringBuilder concated = new StringBuilder().append(secretkey);
concated.append("extraParams").append(polyvDetails.getExtraParams())
.append("ts").append(polyvDetails.getTs())
.append("userId").append(secretId)
.append("videoId").append(polyvDetails.getVideoId())
.append("viewerId").append(polyvDetails.getUserId())
.append("viewerIp").append(polyvDetails.getIp())
.append("viewerName").append(polyvDetails.getUsername()).append(secretkey);
String sign = this.MD5Code(concated.toString().trim());
OkHttpClient client = new OkHttpClient();
FormBody body = new FormBody.Builder()
.add("userId", secretId)
.add("videoId", polyvDetails.getVideoId())
.add("ts", String.valueOf(polyvDetails.getTs()))
.add("viewerIp", polyvDetails.getIp())
.add("viewerName", polyvDetails.getUsername())
.add("extraParams", polyvDetails.getExtraParams())
.add("viewerId", String.valueOf(polyvDetails.getUserId()))
.add("sign", sign)
.build();
Request request = new Request.Builder().addHeader("Content-type", "application/x-www-form-urlencoded")
.url(url).post(body).build();
try {
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
String result = response.body().string();
logger.debug("****************content:" + result);
Document document = Document.parse(result);
Document document1 = (Document) document.get("data");
HzsPolyvTokenEntity polyvTokenEntity1 = new HzsPolyvTokenEntity();
polyvTokenEntity1.setToken(document1.get("token").toString());
polyvTokenEntity1.setVideoId(document1.get("videoId").toString());
polyvTokenEntityList.add(polyvTokenEntity1);
} else {
logger.debug("*********" + response.body().string());
throw new IllegalArgumentException("get polyv interface failed!");
}
} catch (IOException e) {
e.printStackTrace();
}
}
return polyvTokenEntityList;
}
```