SpringBoot 使用OKhttp
pom
<!-- Okhttp -->
<dependency>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
<version>3.6.0</version>
</dependency>
<!-- =======end======-->
StateCallBack
public interface StateCallBack {
void onSuccess(String json);
void onFail(String e);
}
HttpUtil
@Component
public class HttpUtil {
@Value("${httputil.postimgurl}")
private String postimgurl;
private OkHttpClient client = null;
private RequestBody requestBody = null;
private Request request = null;
private Logger log = LoggerFactory.getLogger(this.getClass());
@PostConstruct
public void init(){
client = new OkHttpClient();
log.info("初始化Okhttp");
}
public void postTakeImg(String base64Img,final StateCallBack back) {
requestBody = new FormBody.Builder()
.add("base64Str", base64Img)
.build();
request = new Request.Builder()
.url(postimgurl)
.post(requestBody)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(okhttp3.Call call, IOException e) {
back.onFail(e.toString());
}
@Override
public void onResponse(okhttp3.Call call, Response response) throws IOException {
String data = response.body().string();
back.onSuccess(data);
}
});
}
}