0

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?

lyc001
  • 777
  • 1
  • 10
  • 25
  • https://github.com/square/okhttp us this (very popular lib) and use the `Interceptor`'s https://github.com/square/okhttp/wiki/Interceptors – Blundell Dec 11 '15 at 15:00
  • how can I know using the interceptor if it is a start of a download or a s start of an upload? @Blundell – lyc001 Dec 14 '15 at 14:45

1 Answers1

0

`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
        }
    }); `
pouya
  • 112
  • 1
  • 8