Android:如何替换不推荐使用的HttpRequestExecutor

问题描述 投票:0回答:1

我正在尝试从我的Android项目中删除HttpClient api,并过渡到使用HttpURLConnection。

在旧的API中,我使用HttpRequestExecutor在应用程序进行下载与上传时更改通知栏中的某些图标

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);
                }
            };
        }
    };

如何使用HttpURLConnection进行相同操作?

java android android-networking androidhttpclient android-httptransport
1个回答
0
投票

`OkHttpClient客户=新的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
        }
    }); `
© www.soinside.com 2019 - 2024. All rights reserved.