Example usage for org.apache.http.client.methods HttpUriRequest getAllHeaders

List of usage examples for org.apache.http.client.methods HttpUriRequest getAllHeaders

Introduction

In this page you can find the example usage for org.apache.http.client.methods HttpUriRequest getAllHeaders.

Prototype

Header[] getAllHeaders();

Source Link

Usage

From source file:net.tsz.afinal.http.HttpHandler.java

private void makeRequestWithRetries(HttpUriRequest request) throws IOException {
    if (isResume && targetUrl != null) {
        File downloadFile = new File(targetUrl);
        long fileLen = 0;
        if (downloadFile.isFile() && downloadFile.exists()) {
            fileLen = downloadFile.length();
        }//w  w w  .ja va  2s.  co  m
        if (fileLen > 0)
            request.setHeader("RANGE", "bytes=" + fileLen + "-");
    }

    boolean retry = true;
    IOException cause = null;
    HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler();//?
    while (retry) {
        try {
            if (isCancelled()) {
                return;
            }

            //POST:?;GET:?
            String requestUrl = request.getURI().toString();
            String requestMethod = request.getMethod();
            ZLogger.d(String.format("<%d><%s> %s", executionCount, requestMethod, requestUrl));

            for (Header header : request.getAllHeaders()) {
                ZLogger.d(String.format("<%s>:<%s>", header.getName(), header.getValue()));
            }

            //??url
            StringBuilder requestParams = new StringBuilder();
            if (requestMethod.equals(POST)) {
                HttpEntityEnclosingRequestBase requestBase = (HttpEntityEnclosingRequestBase) request;
                if (requestBase != null) {
                    HttpEntity entity = requestBase.getEntity();
                    if (entity != null) {
                        InputStream is = entity.getContent();
                        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                        String line = null;
                        try {
                            while ((line = reader.readLine()) != null) {
                                //                            sb.append(line + "/n");
                                //                                Log.d("Nat: makeRequestWithRetries.request.Params.line", line);
                                requestParams.append(line);
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                            ZLogger.ef(e.toString());
                        } finally {
                            try {
                                is.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                    //                        byte[] paramsArray = EntityUtils.toByteArray(entity);
                    //                        String paramsStr = EntityUtils.toString(entity, "UTF-8");
                    //                        Log.d("Nat: makeRequestWithRetries.request.Params(2)", paramsStr);
                    //                        Log.d("Nat: makeRequestWithRetries.request.Params(3)", EntityUtils.toString(entity));
                }

                //                    Log.d("Nat: makeRequestWithRetries.request.Params(RAW)", requestParams.toString());
            }

            //
            HttpResponse response = client.execute(request, context);
            //                for(Header header : response.getAllHeaders()){
            //                    Log.d("Nat", String.format(" makeRequestWithRetries.respoonse.header <%s><%s>", header.getName(), header.getValue()));
            //                }

            if (isCancelled()) {
                ZLogger.d("Nat: makeRequestWithRetries", "request caneled.");
                return;
            }

            //POST:?;GET:?
            request.getRequestLine();//GET
            ZLogger.d(request.getRequestLine().toString());
            /*if (request.getMethod().equals("post")) {
            HttpParams params = request.getParams();
             params.setParameter(NetFactory.CLIENTSESSION, "");
            request.snetParams(params);
            }*/

            //?????()
            //executionCount < 1,?????
            if (response.containsHeader("needLogin")/* && executionCount < 1*/) {
                //?url?JSSIONID??cookie.
                //?(?),sessionId
                String newSid = MfhLoginService.get().doLogin();
                if (newSid == null) {
                    //TODO
                    //,?
                    //                        Intent intent = new Intent(Constants.ACTION_REDIRECT_TO_LOGIN_H5);
                    //                        BizApplication.getAppContext().sendBroadcast(intent);
                    //                        break;
                } else {
                    String cookie = String.format("%s=%s", FinalHttp.KEY_JSESSIONID, newSid);
                    request.addHeader(FinalHttp.HEADER_SET_COOKIE, cookie);
                    request.addHeader(FinalHttp.HEADER_COOKIE, cookie);
                    request.addHeader(FinalHttp.HEADER_cookie, cookie);
                    // ?
                    //                        MsgBridgeUtil.register();

                    if (requestMethod.equals(POST)) {
                        //                        //EntityJSSIONID
                        String newParams = replaceParam(requestParams.toString(), JSESSIONID, newSid);
                        //                            HttpEntity entity = new StringEntity(newParams);
                        HttpEntity entity = convertToAjaxParams(newParams).getEntity();
                        ((HttpEntityEnclosingRequestBase) request).setEntity(entity);
                    } else if (requestMethod.equals(GET)) {
                        //URLJSSIONID
                        String newRequestUrl = replaceParam(requestUrl, JSESSIONID, newSid);
                        //                            newRequestUrl = replaceParam(newRequestUrl, "lastupdate", "0");
                        URI uri = new URI(newRequestUrl);
                        //                            Log.d("Nat: makeRequestWithRetries.autoLogin.URI", uri.toString());
                        //                                HttpEntityEnclosingRequestBase requestFact = (HttpEntityEnclosingRequestBase)request;
                        //                                requestFact.setURI(uri);
                        ((HttpEntityEnclosingRequestBase) request).setURI(uri);
                    }
                }

                //TODO,?
                retry = (++executionCount <= MAX_RETRY_TIMES)
                        || retryHandler.retryRequest(new IOException("Exception"), executionCount, context);
                //                    ZLogger.d(String.format("%s  %d", retry ? "?" : "??", executionCount));
                if (retry) {
                    continue;
                }
            }

            //?
            handleResponse(response);
            return;
        } catch (UnknownHostException e) {
            ZLogger.e("UnknownHostException:" + e.toString());
            publishProgress(UPDATE_FAILURE, e, "unknownHostExceptioncan't resolve host");
            return;
        } catch (IOException e) {
            ZLogger.e("IOException: " + e.toString());
            cause = e;
            retry = retryHandler.retryRequest(cause, ++executionCount, context);
            publishProgress(UPDATE_FAILURE, e, "unknownHostExceptioncan't resolve host");
        } catch (NullPointerException e) {
            if (e != null) {
                ZLogger.e("NullPointerException: " + e.toString());
                // here's a bug in HttpClient 4.0.x that on some occasions causes
                // DefaultRequestExecutor to throw an NPE, see
                // http://code.google.com/p/android/issues/detail?id=5255
                cause = new IOException("NPE in HttpClient: " + e.getMessage());
                retry = retryHandler.retryRequest(cause, ++executionCount, context);
            } else {
                ZLogger.e("NullPointerException: e is null");
            }
            publishProgress(UPDATE_FAILURE, e, "unknownHostExceptioncan't resolve host");
        } catch (Exception e) {
            ZLogger.e("Exception: " + e.toString());
            cause = new IOException("Unhandled Exception" + e.getMessage());
            retry = retryHandler.retryRequest(cause, ++executionCount, context);
            publishProgress(UPDATE_FAILURE, e, "unknownHostExceptioncan't resolve host");
        }
    }

    // cleaned up to throw IOException
    if (cause != null) {
        throw cause;
    }
    //        else{
    //            //TODO
    //            throw new IOException("");
    //        }
}

From source file:org.dasein.cloud.azure.tests.compute.vm.AzureVmTest.java

@Test
public void testListVMMakesTheCorrectNumberOfAPICalls() throws CloudException, InternalException {

    ArrayList<HostedServiceModel> hostedServiceModelList = new ArrayList<HostedServiceModel>();
    for (Integer i = 1; i < 20; i++) {
        final HostedServiceModel hostedServiceModel = new HostedServiceModel();
        hostedServiceModel.setServiceName(String.format("HOSTED_SERVICE_%s", i.toString()));
        hostedServiceModel.setUrl("TEST_SERVICE_URL");
        hostedServiceModelList.add(hostedServiceModel);
    }/*from   w  ww .  java  2 s.c o m*/
    HostedServicesModel hostedServicesModel = new HostedServicesModel();
    hostedServicesModel.setHostedServiceModelList(hostedServiceModelList);
    final DaseinObjectToXmlEntity<HostedServicesModel> responseEntity = new DaseinObjectToXmlEntity<HostedServicesModel>(
            hostedServicesModel);

    final CloseableHttpResponse getHttpResponseHostedServicesEntityMock = getHttpResponseMock(
            getStatusLineMock(HttpServletResponse.SC_OK), responseEntity, new Header[] {});
    final CloseableHttpResponse getHttpResponseEmptyEntityMock = getHttpResponseMock(
            getStatusLineMock(HttpServletResponse.SC_OK), null, new Header[] {});

    final String expectedUrl = String.format(HOSTED_SERVICES_URL, ENDPOINT, ACCOUNT_NO);
    final ArrayList<String> actualAPICallUrls = new ArrayList<String>();
    new MockUp<CloseableHttpClient>() {
        @Mock
        public CloseableHttpResponse execute(HttpUriRequest request) throws IOException {
            if (request.getURI().toString().endsWith("hostedservices")) {
                assertGet(request, expectedUrl, new Header[] { new BasicHeader("x-ms-version", "2012-03-01") });
                return getHttpResponseHostedServicesEntityMock;
            } else if (request.getURI().toString().endsWith("embed-detail=true")) {
                Assert.assertNotNull(
                        CollectionUtils.find(Arrays.asList(request.getAllHeaders()), new Predicate() {
                            @Override
                            public boolean evaluate(Object object) {
                                Header actualHeader = (Header) object;
                                return actualHeader.getName() == "x-ms-version"
                                        && actualHeader.getValue() == "2014-05-01";
                            }
                        }));
                actualAPICallUrls.add(request.getURI().toString());
                return getHttpResponseEmptyEntityMock;
            } else {
                Assert.fail("listVirtualMachine method makes an unexpected API call");
                return null;
            }
        }
    };

    AzureVM azureVM = new AzureVM(azureMock);
    Iterable<VirtualMachine> virtualMachines = azureVM.listVirtualMachines();

    Assert.assertNotNull(virtualMachines);
    assertEquals(hostedServicesModel.getHostedServiceModelList().size(), actualAPICallUrls.size());
    for (HostedServiceModel hostedServiceModel : hostedServicesModel.getHostedServiceModelList()) {
        String expectedUrlCall = String.format(HOSTED_SERVICES_SERVICE_EMBEDED_DETAILS_URL, ENDPOINT,
                ACCOUNT_NO, hostedServiceModel.getServiceName());
        assertTrue(actualAPICallUrls.contains(expectedUrlCall));
    }
    assertEquals(0, IteratorUtils.toList(virtualMachines.iterator()).size());
}