I am trying to remove the HttpClient api from my Android project and to transition to using HttpURLConnection.
In the old API, I made use of HttpRequestExecutor, to change some icon in the notification bar when the app is downloading vs uploading
this.httpclient = new DefaultHttpClient(httpParameters){
@Override
protected HttpRequestExecutor createRequestExecutor() {
return new HttpRequestExecutor(){
@Override
protected HttpResponse doSendRequest(HttpRequest request,
HttpClientConnection conn, HttpContext http_context)
throws IOException, HttpException {
EventsBroadcaster.broadcastConnectionUploading(context);
return super.doSendRequest(request, conn, http_context);
}
@Override
protected HttpResponse doReceiveResponse(
HttpRequest request, HttpClientConnection conn,
HttpContext http_context) throws HttpException,
IOException {
EventsBroadcaster.broadcastConnectionDownloading(context);
return super.doReceiveResponse(request, conn, http_context);
}
};
}
};
How can I do the same with HttpURLConnection?
`OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
RequestBody body = RequestBody.create(mediaType, "Your Body");
Request request = new Request.Builder()
.url("Your url")
.post(body)
.addHeader("add as many add headers as u want")
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
//What should happen if failed
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
//what should happen if it is successful
}
}); `
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.