Java Examples for org.apache.http.client.methods.HttpRequestBase

The following java examples will help you to understand the usage of org.apache.http.client.methods.HttpRequestBase. These source code samples are taken from different open source projects.

Example 1
Project: common_utils-master  File: Stock.java View source code
@Test
public void testStock() throws Exception {
    System.out.println(System.currentTimeMillis());
    HttpRequestBase requestBase = HttpBuilder.newBuilder().url("http://query.sse.com.cn/commonQuery.do?isPagination=true&sqlId=COMMON_SSE_ZQPZ_GPLB_MCJS_SSAG_L&pageHelp.pageSize=100000&pageHelp.pageNo=1&pageHelp.beginPage=1&pageHelp.endPage=100&_=" + System.currentTimeMillis()).header("Referer", "http://www.sse.com.cn/assortment/stock/list/name/").get().build();
    String rs = HttpAccess.execute(HttpAccess.getClient(), requestBase);
    EntityHelper.print(rs);
//        HttpRequestBase requestBase = HttpBuilder.newBuilder().url("http://quote.eastmoney.com/search.html?stockcode=30054").get().build();
//        InputStream inputStream = HttpAccess.executeAndGetInputStream(HttpAccess.getClient(), requestBase);
//        FileOutputStream outputStream = new FileOutputStream(new File("a.html"));
//        byte[] buffer = new byte[1024];
//        int len;
//        try {
//            while ((len = inputStream.read(buffer)) > -1) {
//                outputStream.write(buffer, 0, len);
//            }
//            outputStream.flush();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
}
Example 2
Project: EasyRestClient-master  File: EasyServiceRequest.java View source code
public HttpRequestBase getHttpRequest(String uri, HttpEntity httpEntity) {
    HttpEntityEnclosingRequestBase httpEntityEnclosingBaseRequest = null;
    switch(requestMethod) {
        case POST:
            httpEntityEnclosingBaseRequest = new HttpPost(uri);
            break;
        case PUT:
            httpEntityEnclosingBaseRequest = new HttpPut(url);
            break;
        case DELETE:
            httpEntityEnclosingBaseRequest = new HttpDeleteWithBody(uri);
            break;
        default:
            return httpEntityEnclosingBaseRequest;
    }
    if (contentType != null)
        httpEntityEnclosingBaseRequest.addHeader("content-type", contentType);
    httpEntityEnclosingBaseRequest.setEntity(httpEntity);
    if (EasyDroid.enableLogging) {
        try {
            Log.d(TAG, EasyCommonUtils.convertStreamToString(httpEntity.getContent()));
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (UnsupportedOperationException e) {
            e.printStackTrace();
        }
    }
    return httpEntityEnclosingBaseRequest;
}
Example 3
Project: RobamVolley-master  File: SyncHttpHandler.java View source code
public ResponseStream sendRequest(HttpRequestBase request) throws HttpException {
    boolean retry = true;
    HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler();
    while (retry) {
        IOException exception = null;
        try {
            requestUrl = request.getURI().toString();
            requestMethod = request.getMethod();
            if (HttpUtils.sHttpCache.isEnabled(requestMethod)) {
                String result = HttpUtils.sHttpCache.get(requestUrl);
                if (result != null) {
                    return new ResponseStream(result);
                }
            }
            HttpResponse response = client.execute(request, context);
            return handleResponse(response);
        } catch (UnknownHostException e) {
            exception = e;
            retry = retryHandler.retryRequest(exception, ++retriedTimes, context);
        } catch (IOException e) {
            exception = e;
            retry = retryHandler.retryRequest(exception, ++retriedTimes, context);
        } catch (NullPointerException e) {
            exception = new IOException(e.getMessage());
            exception.initCause(e);
            retry = retryHandler.retryRequest(exception, ++retriedTimes, context);
        } catch (HttpException e) {
            throw e;
        } catch (Throwable e) {
            exception = new IOException(e.getMessage());
            exception.initCause(e);
            retry = retryHandler.retryRequest(exception, ++retriedTimes, context);
        }
        if (!retry && exception != null) {
            throw new HttpException(exception);
        }
    }
    return null;
}
Example 4
Project: SocialSDK-master  File: SmartCloudService.java View source code
@Override
protected void prepareRequest(HttpClient httpClient, HttpRequestBase httpRequestBase, Args args, Content content) throws ClientServicesException {
    Object contents = args.getHandler();
    if (contents instanceof File) {
        String name = args.getParameters().get("file");
        FileEntity fileEnt = new FileEntity((File) contents, getMimeForUpload());
        //fileEnt.setContentEncoding(FORMAT_BINARY);
        httpRequestBase.setHeader("slug", name);
        httpRequestBase.setHeader("Content-type", getMimeForUpload());
        if (fileEnt != null && (httpRequestBase instanceof HttpEntityEnclosingRequestBase)) {
            ((HttpEntityEnclosingRequestBase) httpRequestBase).setEntity(fileEnt);
        }
    }
    // TODO Auto-generated method stub
    super.prepareRequest(httpClient, httpRequestBase, args, content);
}
Example 5
Project: EECE496-master  File: HttpUtils.java View source code
public static void setRequestOptions(HttpRequestBase request, HttpRequestOptions requestOptions) {
    request.getParams().setParameter(AllClientPNames.MAX_REDIRECTS, new Integer(requestOptions.getMaxRedirects()));
    request.getParams().setParameter(AllClientPNames.SO_TIMEOUT, new Integer(requestOptions.getSocketTimeout()));
    request.getParams().setParameter(AllClientPNames.CONNECTION_TIMEOUT, new Integer(requestOptions.getConnTimeout()));
    request.getParams().setParameter(AllClientPNames.ALLOW_CIRCULAR_REDIRECTS, Boolean.valueOf(requestOptions.getAllowCircularRedirects()));
    Map requestHeaders = requestOptions.getRequestHeaders();
    if (requestHeaders != null) {
        Iterator iter = requestHeaders.keySet().iterator();
        String headerName;
        while (iter.hasNext()) {
            headerName = (String) iter.next();
            request.addHeader(headerName, (String) requestHeaders.get(headerName));
        }
    }
}
Example 6
Project: nem.core-master  File: HttpErrorResponseDeserializerUnionStrategyTest.java View source code
private static ErrorResponseDeserializerUnion coerceUnion(final int statusCode, final byte[] serializedBytes, final DeserializationContext context) throws IOException {
    // Arrange:
    final HttpErrorResponseDeserializerUnionStrategy strategy = new HttpErrorResponseDeserializerUnionStrategy(context);
    final HttpResponse response = Mockito.mock(HttpResponse.class);
    ConnectUtils.mockStatusCode(response, statusCode);
    final HttpEntity entity = Mockito.mock(HttpEntity.class);
    final ByteArrayInputStream inputStream = new ByteArrayInputStream(serializedBytes);
    Mockito.when(response.getEntity()).thenReturn(entity);
    Mockito.when(entity.getContent()).thenReturn(inputStream);
    // Act:
    return strategy.coerce(Mockito.mock(HttpRequestBase.class), response);
}
Example 7
Project: openid4java-openidorgfix-master  File: HttpUtils.java View source code
public static void setRequestOptions(HttpRequestBase request, HttpRequestOptions requestOptions) {
    request.getParams().setParameter(AllClientPNames.MAX_REDIRECTS, new Integer(requestOptions.getMaxRedirects()));
    request.getParams().setParameter(AllClientPNames.SO_TIMEOUT, new Integer(requestOptions.getSocketTimeout()));
    request.getParams().setParameter(AllClientPNames.CONNECTION_TIMEOUT, new Integer(requestOptions.getConnTimeout()));
    request.getParams().setParameter(AllClientPNames.ALLOW_CIRCULAR_REDIRECTS, Boolean.valueOf(requestOptions.getAllowCircularRedirects()));
    Map requestHeaders = requestOptions.getRequestHeaders();
    if (requestHeaders != null) {
        Iterator iter = requestHeaders.keySet().iterator();
        String headerName;
        while (iter.hasNext()) {
            headerName = (String) iter.next();
            request.addHeader(headerName, (String) requestHeaders.get(headerName));
        }
    }
}
Example 8
Project: socom-master  File: FBPostRequest.java View source code
private HttpRequestBase buildHttpPostRequest() throws URISyntaxException {
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    includePostParameterMap(builder);
    HttpEntity entity = builder.build();
    HttpPost post = new HttpPost(getRequestUrl());
    post.setEntity(entity);
    return post;
}
Example 9
Project: webBee-master  File: HttpResponse.java View source code
public CloseableHttpResponse getResponse() {
    CloseableHttpResponse closeableHttpResponse = null;
    try {
        Setting setting = task.getSetting();
        HttpRequestBase httpMethod;
        httpMethod = HttpClientPool.getInstance().generateHttpMethod(request, task, null);
        HttpClientBuilder httpClientBuilder = HttpClientPool.getInstance().generateClient(setting, httpMethod);
        CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
        closeableHttpResponse = closeableHttpClient.execute(httpMethod);
    } catch (IOException e) {
        e.printStackTrace();
        System.out.println(e);
    }
    return closeableHttpResponse;
}
Example 10
Project: weixin4j-master  File: HttpComponent4_2.java View source code
@Override
public HttpResponse execute(HttpRequest request) throws HttpClientException {
    HttpResponse response = null;
    try {
        HttpRequestBase uriRequest = createRequest(request);
        CloseableHttpResponse httpResponse = httpClient.execute(uriRequest);
        response = new HttpComponent4_2Response(httpResponse, getContent(httpResponse));
        handleResponse(response);
    } catch (IOException e) {
        throw new HttpClientException("I/O error on " + request.getMethod().name() + " request for \"" + request.getURI().toString(), e);
    } finally {
        if (response != null) {
            response.close();
        }
    }
    return response;
}
Example 11
Project: ActionGenerator-master  File: HttpUtils.java View source code
public static boolean processRequestSilently(HttpClient httpClient, HttpRequestBase request) {
    try {
        HttpResponse response = httpClient.execute(request);
        LOG.info("Event sent");
        if (HttpStatus.SC_OK != response.getStatusLine().getStatusCode()) {
            return false;
        }
        HttpEntity entity = response.getEntity();
        EntityUtils.consume(entity);
        return true;
    } catch (IOException e) {
        LOG.error("Sending event failed", e);
        return false;
    } finally {
        request.releaseConnection();
    }
}
Example 12
Project: android-open-project-demo-master  File: SyncHttpHandler.java View source code
public ResponseStream sendRequest(HttpRequestBase request) throws HttpException {
    HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler();
    while (true) {
        boolean retry = true;
        IOException exception = null;
        try {
            requestUrl = request.getURI().toString();
            requestMethod = request.getMethod();
            if (HttpUtils.sHttpCache.isEnabled(requestMethod)) {
                String result = HttpUtils.sHttpCache.get(requestUrl);
                if (result != null) {
                    return new ResponseStream(result);
                }
            }
            HttpResponse response = client.execute(request, context);
            return handleResponse(response);
        } catch (UnknownHostException e) {
            exception = e;
            retry = retryHandler.retryRequest(exception, ++retriedTimes, context);
        } catch (IOException e) {
            exception = e;
            retry = retryHandler.retryRequest(exception, ++retriedTimes, context);
        } catch (NullPointerException e) {
            exception = new IOException(e.getMessage());
            exception.initCause(e);
            retry = retryHandler.retryRequest(exception, ++retriedTimes, context);
        } catch (HttpException e) {
            throw e;
        } catch (Throwable e) {
            exception = new IOException(e.getMessage());
            exception.initCause(e);
            retry = retryHandler.retryRequest(exception, ++retriedTimes, context);
        }
        if (!retry) {
            throw new HttpException(exception);
        }
    }
}
Example 13
Project: android-project-Demo-master  File: SyncHttpHandler.java View source code
public ResponseStream sendRequest(HttpRequestBase request) throws HttpException {
    HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler();
    while (true) {
        boolean retry = true;
        IOException exception = null;
        try {
            requestUrl = request.getURI().toString();
            requestMethod = request.getMethod();
            if (HttpUtils.sHttpCache.isEnabled(requestMethod)) {
                String result = HttpUtils.sHttpCache.get(requestUrl);
                if (result != null) {
                    return new ResponseStream(result);
                }
            }
            HttpResponse response = client.execute(request, context);
            return handleResponse(response);
        } catch (UnknownHostException e) {
            exception = e;
            retry = retryHandler.retryRequest(exception, ++retriedTimes, context);
        } catch (IOException e) {
            exception = e;
            retry = retryHandler.retryRequest(exception, ++retriedTimes, context);
        } catch (NullPointerException e) {
            exception = new IOException(e.getMessage());
            exception.initCause(e);
            retry = retryHandler.retryRequest(exception, ++retriedTimes, context);
        } catch (HttpException e) {
            throw e;
        } catch (Throwable e) {
            exception = new IOException(e.getMessage());
            exception.initCause(e);
            retry = retryHandler.retryRequest(exception, ++retriedTimes, context);
        }
        if (!retry) {
            throw new HttpException(exception);
        }
    }
}
Example 14
Project: antiope-master  File: YahooBaseClient.java View source code
private HttpResponse createResponse(HttpRequestBase method, Request<?> request, org.apache.http.HttpResponse apacheHttpResponse) throws IOException {
    HttpResponse httpResponse = new //request, 
    HttpResponse(method);
    if (apacheHttpResponse.getEntity() != null) {
        httpResponse.setContent(apacheHttpResponse.getEntity().getContent());
    }
    httpResponse.setStatusCode(apacheHttpResponse.getStatusLine().getStatusCode());
    httpResponse.setStatusText(apacheHttpResponse.getStatusLine().getReasonPhrase());
    for (Header header : apacheHttpResponse.getAllHeaders()) {
        httpResponse.addHeader(header.getName(), header.getValue());
    }
    return httpResponse;
}
Example 15
Project: AppAssit-master  File: SyncHttpHandler.java View source code
public ResponseStream sendRequest(HttpRequestBase request) throws HttpException {
    HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler();
    while (true) {
        boolean retry = true;
        IOException exception = null;
        try {
            requestUrl = request.getURI().toString();
            requestMethod = request.getMethod();
            if (HttpUtils.sHttpCache.isEnabled(requestMethod)) {
                String result = HttpUtils.sHttpCache.get(requestUrl);
                if (result != null) {
                    return new ResponseStream(result);
                }
            }
            HttpResponse response = client.execute(request, context);
            return handleResponse(response);
        } catch (UnknownHostException e) {
            exception = e;
            retry = retryHandler.retryRequest(exception, ++retriedTimes, context);
        } catch (IOException e) {
            exception = e;
            retry = retryHandler.retryRequest(exception, ++retriedTimes, context);
        } catch (NullPointerException e) {
            exception = new IOException(e.getMessage());
            exception.initCause(e);
            retry = retryHandler.retryRequest(exception, ++retriedTimes, context);
        } catch (HttpException e) {
            throw e;
        } catch (Throwable e) {
            exception = new IOException(e.getMessage());
            exception.initCause(e);
            retry = retryHandler.retryRequest(exception, ++retriedTimes, context);
        }
        if (!retry) {
            throw new HttpException(exception);
        }
    }
}
Example 16
Project: bosi-android-master  File: SyncHttpHandler.java View source code
public ResponseStream sendRequest(HttpRequestBase request) throws HttpException {
    HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler();
    while (true) {
        boolean retry = true;
        IOException exception = null;
        try {
            requestUrl = request.getURI().toString();
            requestMethod = request.getMethod();
            if (HttpUtils.sHttpCache.isEnabled(requestMethod)) {
                String result = HttpUtils.sHttpCache.get(requestUrl);
                if (result != null) {
                    return new ResponseStream(result);
                }
            }
            HttpResponse response = client.execute(request, context);
            return handleResponse(response);
        } catch (UnknownHostException e) {
            exception = e;
            retry = retryHandler.retryRequest(exception, ++retriedTimes, context);
        } catch (IOException e) {
            exception = e;
            retry = retryHandler.retryRequest(exception, ++retriedTimes, context);
        } catch (NullPointerException e) {
            exception = new IOException(e.getMessage());
            exception.initCause(e);
            retry = retryHandler.retryRequest(exception, ++retriedTimes, context);
        } catch (HttpException e) {
            throw e;
        } catch (Throwable e) {
            exception = new IOException(e.getMessage());
            exception.initCause(e);
            retry = retryHandler.retryRequest(exception, ++retriedTimes, context);
        }
        if (!retry) {
            throw new HttpException(exception);
        }
    }
}
Example 17
Project: deepnighttwo-master  File: HttpRequestUtil.java View source code
public static void addHeaders(HttpRequestBase req, String headerStr) {
    String[] headers = headerStr.split("\\n");
    for (String header : headers) {
        int index = header.indexOf(':');
        String key = header.substring(0, index).trim();
        if ("Content-Length".equals(key)) {
            continue;
        }
        String value = header.substring(index + 1).trim();
        req.setHeader(key, value);
    }
}
Example 18
Project: forplay-master  File: AndroidNet.java View source code
private void doHttp(boolean isPost, String url, String data, Callback callback) {
    // TODO: use AsyncTask
    HttpClient httpclient = new DefaultHttpClient();
    HttpRequestBase req = null;
    if (isPost) {
        HttpPost httppost = new HttpPost(url);
        if (data != null) {
            try {
                httppost.setEntity(new StringEntity(data));
            } catch (UnsupportedEncodingException e) {
                callback.failure(e);
            }
        }
        req = httppost;
    } else {
        req = new HttpGet(url);
    }
    try {
        HttpResponse response = httpclient.execute(req);
        callback.success(EntityUtils.toString(response.getEntity()));
    } catch (Exception e) {
        callback.failure(e);
    }
}
Example 19
Project: galaxy-fds-sdk-android-master  File: SignatureCredential.java View source code
@Override
public void addHeader(HttpRequestBase request) throws GalaxyFDSClientException {
    request.setHeader(Common.DATE, DATE_FORMAT.get().format(new Date()));
    try {
        URI uri = request.getURI();
        LinkedListMultimap<String, String> httpHeaders = LinkedListMultimap.create();
        for (Header httpHeader : request.getAllHeaders()) {
            httpHeaders.put(httpHeader.getName(), httpHeader.getValue());
        }
        HttpMethod httpMethod = HttpMethod.valueOf(request.getMethod());
        request.setHeader(HttpHeaders.AUTHORIZATION, Signer.getAuthorizationHeader(httpMethod, uri, httpHeaders, accessKeyId, secretAccessKeyId, SignAlgorithm.HmacSHA1));
    } catch (NoSuchAlgorithmException e) {
        throw new GalaxyFDSClientException("Fail to get signature for request:" + request, e);
    } catch (InvalidKeyException e) {
        throw new GalaxyFDSClientException("Fail to get signature for request:" + request, e);
    }
}
Example 20
Project: ishacrmserver-master  File: MandrillRequest.java View source code
public final HttpRequestBase getRequest() throws IOException {
    final String paramsStr = LutungGsonUtils.getGson().toJson(requestParams, requestParams.getClass());
    log.debug("raw content for request:\n" + paramsStr);
    final StringEntity entity = new StringEntity(paramsStr, "UTF-8");
    entity.setContentType("application/json");
    final HttpPost request = new HttpPost(url);
    request.setEntity(entity);
    return request;
}
Example 21
Project: keycloak-master  File: HttpAdapterUtils.java View source code
public static <T> T sendJsonHttpRequest(KeycloakDeployment deployment, HttpRequestBase httpRequest, Class<T> clazz) throws HttpClientAdapterException {
    try {
        HttpResponse response = deployment.getClient().execute(httpRequest);
        int status = response.getStatusLine().getStatusCode();
        if (status != 200) {
            close(response);
            throw new HttpClientAdapterException("Unexpected status = " + status);
        }
        HttpEntity entity = response.getEntity();
        if (entity == null) {
            throw new HttpClientAdapterException("There was no entity.");
        }
        InputStream is = entity.getContent();
        try {
            return JsonSerialization.readValue(is, clazz);
        } finally {
            try {
                is.close();
            } catch (IOException ignored) {
            }
        }
    } catch (IOException e) {
        throw new HttpClientAdapterException("IO error", e);
    }
}
Example 22
Project: meetup-client-master  File: ApiaryHttpRequestConfiguration.java View source code
public void addHeaders(HttpRequestBase httprequestbase) {
    String s;
    String s1;
    String s2;
    httprequestbase.addHeader("Accept-Encoding", "gzip");
    httprequestbase.addHeader("Accept-Language", Locale.getDefault().toString());
    httprequestbase.addHeader("User-Agent", getUserAgentHeader(mContext));
    httprequestbase.addHeader("Content-Type", mContentType);
    if (mAccount != null) {
        try {
            ApiaryAuthDataFactory.ApiaryAuthData apiaryauthdata = ApiaryAuthDataFactory.getAuthData(mScope);
            s1 = apiaryauthdata.getAuthToken(mContext, mAccount.getName());
            s2 = Long.toString(apiaryauthdata.getAuthTime(s1).longValue());
        } catch (Exception exception) {
            throw new RuntimeException("Cannot obtain authentication token", exception);
        }
        httprequestbase.addHeader("Authorization", (new StringBuilder("Bearer ")).append(s1).toString());
        httprequestbase.addHeader("X-Auth-Time", s2);
    }
    s = RealTimeChatService.getStickyC2dmId(mContext);
    if (s != null)
        httprequestbase.addHeader("X-Android-App-ID", s);
    if (!TextUtils.isEmpty(mBackendOverrideUrl)) {
        if (EsLog.isLoggable("HttpTransaction", 3))
            Log.d("HttpTransaction", (new StringBuilder("Setting backend override url ")).append(mBackendOverrideUrl).toString());
        httprequestbase.addHeader("X-Google-Backend-Override", mBackendOverrideUrl);
    }
}
Example 23
Project: salesforce-plugin-master  File: ConnectionManagerService.java View source code
@Override
protected <Response extends AbstractJSONObject> Response execute(HttpRequestBase request, Class<Response> responseClass) {
    try {
        return super.execute(request, responseClass);
    } catch (ConnectionSessionException e) {
        soapClientService.login();
        setSessionDetails(soapClientService.getSessionId(), soapClientService.getServiceHost());
        return super.execute(request, responseClass);
    }
}
Example 24
Project: SOAP-master  File: EndpointRequestFilterTest.java View source code
@Test
public void doesNotDoubleEncodeAlreadyEncodedUri() throws URISyntaxException {
    String encodedUri = "http://user:password@google.se/search?q=%3F";
    HttpRequestBase httpMethod = Mockito.mock(HttpRequestBase.class);
    SubmitContext context = mockContext(httpMethod);
    AbstractHttpRequest<?> request = mockRequest(encodedUri, mockSettings());
    endpointRequestFilter.filterAbstractHttpRequest(context, request);
    ArgumentCaptor<URI> httpMethodUri = ArgumentCaptor.forClass(URI.class);
    Mockito.verify(httpMethod).setURI(httpMethodUri.capture());
    Assert.assertThat(httpMethodUri.getValue(), Is.is(new URI(encodedUri)));
}
Example 25
Project: soapui-master  File: EndpointRequestFilterTest.java View source code
@Test
public void doesNotDoubleEncodeAlreadyEncodedUri() throws URISyntaxException {
    String encodedUri = "http://user:password@google.se/search?q=%3F";
    HttpRequestBase httpMethod = Mockito.mock(HttpRequestBase.class);
    SubmitContext context = mockContext(httpMethod);
    AbstractHttpRequest<?> request = mockRequest(encodedUri, mockSettings());
    endpointRequestFilter.filterAbstractHttpRequest(context, request);
    ArgumentCaptor<URI> httpMethodUri = ArgumentCaptor.forClass(URI.class);
    Mockito.verify(httpMethod).setURI(httpMethodUri.capture());
    Assert.assertThat(httpMethodUri.getValue(), Is.is(new URI(encodedUri)));
}
Example 26
Project: SpiderJackson-master  File: RequestTask.java View source code
@Override
public String doRequest(CloseableHttpClient client, HttpRequestBase requestBase) throws IOException {
    logger.info("请求 url:{}", getUrl().getUrl());
    startTime = System.currentTimeMillis();
    if (getProxy() != null) {
        response = client.execute(new HttpHost(getProxy().getHost(), getProxy().getPort()), requestBase);
    } else {
        response = client.execute(requestBase);
    }
    response = client.execute(requestBase);
    endTime = System.currentTimeMillis();
    logger.info("endTime:", endTime);
    //EntityUtils.toString(entity, "utf-8");
    return "";
}
Example 27
Project: sputnik-master  File: HttpConnector.java View source code
@NotNull
public CloseableHttpResponse logAndExecute(@NotNull HttpRequestBase request) throws IOException {
    log.info("Request  {}: {} to {}", ++REQUEST_COUNTER, request.getMethod(), request.getURI().toString());
    CloseableHttpResponse httpResponse = httpClient.execute(request, httpClientContext);
    log.info("Response {}: {}", REQUEST_COUNTER, httpResponse.getStatusLine().toString());
    return httpResponse;
}
Example 28
Project: xUtils-master  File: SyncHttpHandler.java View source code
public ResponseStream sendRequest(HttpRequestBase request) throws HttpException {
    HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler();
    while (true) {
        boolean retry = true;
        IOException exception = null;
        try {
            requestUrl = request.getURI().toString();
            requestMethod = request.getMethod();
            if (HttpUtils.sHttpCache.isEnabled(requestMethod)) {
                String result = HttpUtils.sHttpCache.get(requestUrl);
                if (result != null) {
                    return new ResponseStream(result);
                }
            }
            HttpResponse response = client.execute(request, context);
            return handleResponse(response);
        } catch (UnknownHostException e) {
            exception = e;
            retry = retryHandler.retryRequest(exception, ++retriedTimes, context);
        } catch (IOException e) {
            exception = e;
            retry = retryHandler.retryRequest(exception, ++retriedTimes, context);
        } catch (NullPointerException e) {
            exception = new IOException(e.getMessage());
            exception.initCause(e);
            retry = retryHandler.retryRequest(exception, ++retriedTimes, context);
        } catch (HttpException e) {
            throw e;
        } catch (Throwable e) {
            exception = new IOException(e.getMessage());
            exception.initCause(e);
            retry = retryHandler.retryRequest(exception, ++retriedTimes, context);
        }
        if (!retry) {
            throw new HttpException(exception);
        }
    }
}
Example 29
Project: basis-master  File: ConstrainedHttpClient.java View source code
/**
     * Executes the http method specified while protecting the http client with a semaphore. If the maximum number
     * of outstanding requests has been reached it will throw a ServiceUnavailableException. The other exceptions are
     * thrown by the standard http client executeMethod.
     *
     * @return
     * @throws ServiceUnavailableException If the limit of concurrent connections has been reached.
     * @throws IOException                 If an I/O (transport) error occurs. Some transport exceptions cannot be recovered from.
     */
public HttpResponse execute(HttpRequestBase request, int timeoutms) throws ServiceUnavailableException, IOException {
    if (semaphore.tryAcquire()) {
        try {
            logger.trace("Semaphore was acquired. Remaining: {} ", semaphore.availablePermits());
            return HttpUtil.execute(request, timeoutms);
        } finally {
            semaphore.release();
        }
    } else {
        throw new ServiceUnavailableException("Reached limit of " + getCurrentRequests() + " concurrent requests");
    }
}
Example 30
Project: bdd-rest-master  File: HttpClientRequest.java View source code
HttpRequestBase getRequestImpl(URI baseUri) {
    HttpRequestBase request = null;
    switch(method) {
        case HEAD:
            request = new HttpHead();
            break;
        case OPTIONS:
            request = new HttpOptions();
            break;
        case GET:
            request = new HttpGet();
            break;
        case POST:
            request = new HttpPost();
            break;
        case PUT:
            request = new HttpPut();
            break;
        case DELETE:
            request = new HttpDelete();
            break;
        case PATCH:
            request = new HttpPatch();
    }
    request.setURI(baseUri.resolve(uri));
    request.setHeaders(headers.toArray(new Header[headers.size()]));
    if (content != null) {
        ((HttpEntityEnclosingRequest) request).setEntity(new ByteArrayEntity(content));
    }
    return request;
}
Example 31
Project: beacon-of-beacons-master  File: HttpUtils.java View source code
/**
     * Executes GET/POST and obtain the response.
     *
     * @param request request
     *
     * @return response
     */
public String executeRequest(HttpRequestBase request) {
    String response = null;
    CloseableHttpResponse res = null;
    try {
        res = httpClient.execute(request);
        StatusLine line = res.getStatusLine();
        int status = line.getStatusCode();
        HttpEntity entity = res.getEntity();
        response = (entity == null) ? null : EntityUtils.toString(entity);
    } catch (IOException ex) {
        logger.error(ex.getMessage());
    } finally {
        try {
            if (res != null) {
                res.close();
            }
        } catch (IOException ex) {
            logger.error(ex.getMessage());
        }
    }
    return response;
}
Example 32
Project: Carpuwl_android-master  File: NetworkHelper.java View source code
private static String executeRestfulApiRequest(HttpRequestBase restfulRequestType) {
    String jsonResult = null;
    HttpClient httpClient = new DefaultHttpClient();
    HttpResponse httpResponse;
    try {
        httpResponse = httpClient.execute(restfulRequestType);
        jsonResult = EntityUtils.toString(httpResponse.getEntity());
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return jsonResult;
}
Example 33
Project: codedx-plugin-master  File: CodeDxRepeatingClient.java View source code
@Override
protected <T> T doHttpRequest(HttpRequestBase request, String path, boolean isXApi, Type responseType, Object requestBody) throws IOException, CodeDxClientException {
    try {
        int fails = 0;
        while (fails < 3) {
            try {
                try {
                    // use a clone to avoid reusing the request object
                    HttpRequestBase clonedRequest = (HttpRequestBase) request.clone();
                    return super.doHttpRequest(clonedRequest, path, isXApi, responseType, requestBody);
                } catch (CloneNotSupportedException e) {
                    throw new IOException("Could not clone request body entity: " + requestBody);
                }
            } catch (CodeDxClientException clientException) {
                fails++;
                logger.println("Attempt " + fails + " " + clientException.getMessage() + " response code: " + clientException.getHttpCode());
                switch(fails) {
                    case 1:
                        logger.println("Trying again after 1 second");
                        Thread.sleep(1000);
                        break;
                    case 2:
                        logger.println("Trying again after 5 seconds");
                        Thread.sleep(5000);
                        break;
                    case 3:
                        logger.println("Trying again after 30 seconds");
                        Thread.sleep(30000);
                        break;
                    default:
                        throw clientException;
                }
            } catch (SocketException socketException) {
                fails++;
                logger.println("Attempt " + fails + " " + socketException.getMessage());
                switch(fails) {
                    case 1:
                        logger.println("Trying again after 1 second");
                        Thread.sleep(1000);
                        break;
                    case 2:
                        logger.println("Trying again after 5 seconds");
                        Thread.sleep(5000);
                        break;
                    case 3:
                        logger.println("Trying again after 30 seconds");
                        Thread.sleep(30000);
                        break;
                    default:
                        throw socketException;
                }
            }
        }
    } catch (InterruptedException i) {
        logger.println("Thread was interrupted while waiting to re-attempt GET");
        throw new CodeDxClientException("GET", path, "Thread was interrupted. Unabled to finish GET", -1, "");
    }
    //This shouldn't happen, but we all know how that assumption turns out.
    throw new CodeDxClientException("GET", path, "GET was unsuccessful for " + path, -1, "");
}
Example 34
Project: components-ness-httpclient-master  File: InternalResponseTest.java View source code
@Test
public void testCaseInsensitiveHeaders() {
    HttpRequestBase req = new HttpGet();
    HttpResponse response = new BasicHttpResponse(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "OK"));
    response.setHeaders(new Header[] { new BasicHeader("namE1", "val1"), new BasicHeader("Name1", "val2"), new BasicHeader("NAME1", "val3") });
    HttpClientResponse clientResponse = new InternalResponse(req, response);
    Map<String, List<String>> expectedAllHeaders = Maps.newHashMap();
    List<String> values = Lists.newArrayList("val1", "val2", "val3");
    expectedAllHeaders.put("namE1", values);
    assertEquals(values, clientResponse.getHeaders("name1"));
    assertEquals(values, clientResponse.getHeaders("naMe1"));
    assertEquals(expectedAllHeaders, clientResponse.getAllHeaders());
}
Example 35
Project: comsat-master  File: FiberOkHttpUtil.java View source code
public static HttpResponse executeInFiber(final OkApacheClient client, final HttpRequestBase req) throws InterruptedException, IOException {
    return FiberUtil.runInFiberChecked(new SuspendableCallable<HttpResponse>() {

        @Override
        public HttpResponse run() throws SuspendExecution, InterruptedException {
            try {
                return client.execute(req);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
    }, IOException.class);
}
Example 36
Project: disconf-master  File: HttpClientUtil.java View source code
/**
     * 处�具体代�请求执行, 入�方法
     *
     * @throws Exception
     */
public static <T> T execute(HttpRequestBase request, HttpResponseCallbackHandler<T> responseHandler) throws Exception {
    CloseableHttpResponse httpclientResponse = null;
    try {
        if (LOGGER.isDebugEnabled()) {
            Header[] headers = request.getAllHeaders();
            for (Header header : headers) {
                LOGGER.debug("request: " + header.getName() + "\t" + header.getValue());
            }
        }
        httpclientResponse = httpclient.execute(request);
        if (LOGGER.isDebugEnabled()) {
            for (Header header : httpclientResponse.getAllHeaders()) {
                LOGGER.debug("response header: {}\t{}", header.getName(), header.getValue());
            }
        }
        // 填充状��
        int statusCode = httpclientResponse.getStatusLine().getStatusCode();
        String requestBody = null;
        if (request instanceof HttpEntityEnclosingRequestBase) {
            HttpEntity requestEntity = ((HttpEntityEnclosingRequestBase) request).getEntity();
            if (requestEntity != null) {
                requestBody = EntityUtils.toString(requestEntity);
            }
        }
        LOGGER.info("execute http request [{}], status code [{}]", requestBody, statusCode);
        if (statusCode != 200) {
            throw new Exception("execute  request failed [" + requestBody + "], statusCode [" + statusCode + "]");
        }
        // 处��应体
        HttpEntity entity = httpclientResponse.getEntity();
        if (entity != null && responseHandler != null) {
            return responseHandler.handleResponse(requestBody, entity);
        } else {
            LOGGER.info("execute response [{}], response empty", requestBody);
        }
        return null;
    } catch (Exception e) {
        throw e;
    } finally {
        if (httpclientResponse != null) {
            try {
                httpclientResponse.close();
            } catch (IOException e) {
            }
        }
    }
}
Example 37
Project: drift-master  File: APIRequestFragment.java View source code
@Override
protected String doInBackground(String... params) {
    Log.d(LOG_TAG, "Received request: " + params[0] + " " + params[1]);
    HttpRequestBase request = null;
    String method = params[0];
    String url = base + params[1];
    if (method.equals("GET")) {
        request = new HttpGet(url);
    } else if (method.equals("POST")) {
        request = new HttpPost(url);
        request.setHeader("Content-Type", "application/x-www-form-urlencoded");
        StringBuilder formDataBuilder = new StringBuilder();
        try {
            for (int i = 1; i < params.length - 1; i++) {
                formDataBuilder.append(Integer.toString(i));
                formDataBuilder.append("=");
                formDataBuilder.append(URLEncoder.encode(params[i + 1], "utf-8"));
                if (i < params.length - 2) {
                    formDataBuilder.append("&");
                }
            }
            ((HttpPost) (request)).setEntity(new StringEntity(formDataBuilder.toString()));
        } catch (UnsupportedEncodingException e) {
            Log.e(LOG_TAG, "Unsupported encoding :(");
        }
    }
    return getRequest(request);
}
Example 38
Project: glaze-http-master  File: SerializableRequest.java View source code
private HttpRequestBase extractEntityEnclosingRequest() {
    HttpRequestBase req;
    req = new HttpEntityEnclosingRequestBase() {

        @Override
        public String getMethod() {
            return method;
        }
    };
    ByteArrayEntity entity = new ByteArrayEntity(entityData);
    if (entityEncoding != null) {
        entity.setContentEncoding(entityEncoding);
    }
    if (entityContentType != null) {
        entity.setContentType(entityContentType);
    }
    ((HttpEntityEnclosingRequest) req).setEntity(entity);
    return req;
}
Example 39
Project: Grendel-Scan-master  File: HttpRequestFactory.java View source code
/**
     * 
     * @param method
     * @param uri
     * @param headers
     * @param body
     * @param version
     * @return
     * @throws URISyntaxException
     */
public static HttpRequest makeNonScanRequest(final String method, final String uri, final Header headers[], final byte[] body, final ProtocolVersion version) {
    HttpRequestBase request = null;
    boolean entity = false;
    if (method.equalsIgnoreCase(HttpGet.METHOD_NAME)) {
        request = new HttpGet(uri);
    } else if (method.equalsIgnoreCase(HttpPut.METHOD_NAME)) {
        entity = true;
        request = new HttpPut(uri);
    } else if (method.equalsIgnoreCase(HttpPost.METHOD_NAME)) {
        request = new HttpPost(uri);
        entity = true;
    } else if (method.equalsIgnoreCase(HttpTrace.METHOD_NAME)) {
        request = new HttpTrace(uri);
    } else if (method.equalsIgnoreCase(HttpOptions.METHOD_NAME)) {
        request = new HttpOptions(uri);
    } else if (method.equalsIgnoreCase(HttpDelete.METHOD_NAME)) {
        request = new HttpDelete(uri);
    } else if (method.equalsIgnoreCase(HttpHead.METHOD_NAME)) {
        request = new HttpHead(uri);
    }
    if (entity && body != null) {
        ((HttpEntityEnclosingRequest) request).setEntity(new ByteArrayEntity(body));
    }
    ProtocolVersion versionToUse = version;
    if (versionToUse == null) {
        versionToUse = HttpRequestWrapper.DEFAULT_PROTOCL_VERSION;
    }
    HttpProtocolParams.setVersion(request.getParams(), versionToUse);
    if (headers != null) {
        request.setHeaders(headers);
    }
    return request;
}
Example 40
Project: hapi-fhir-master  File: GZipContentInterceptor.java View source code
@Override
public void interceptRequest(IHttpRequest theRequestInterface) {
    HttpRequestBase theRequest = ((ApacheHttpRequest) theRequestInterface).getApacheRequest();
    if (theRequest instanceof HttpEntityEnclosingRequest) {
        Header[] encodingHeaders = theRequest.getHeaders(Constants.HEADER_CONTENT_ENCODING);
        if (encodingHeaders == null || encodingHeaders.length == 0) {
            HttpEntityEnclosingRequest req = (HttpEntityEnclosingRequest) theRequest;
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            GZIPOutputStream gos;
            try {
                gos = new GZIPOutputStream(bos);
                req.getEntity().writeTo(gos);
                gos.finish();
            } catch (IOException e) {
                ourLog.warn("Failed to GZip outgoing content", e);
                return;
            }
            byte[] byteArray = bos.toByteArray();
            ByteArrayEntity newEntity = new ByteArrayEntity(byteArray);
            req.setEntity(newEntity);
            req.addHeader(Constants.HEADER_CONTENT_ENCODING, "gzip");
        }
    }
}
Example 41
Project: hera-master  File: HttpClientBeanProcessor.java View source code
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    MetricTraceContext ctx = MetricTraceContextHolder.getMetricTraceContext();
    if (ctx != null && sign.get() == null && "execute".equals(method.getName())) {
        for (Object each : args) {
            if (each instanceof HttpRequestBase) {
                HttpRequestBase httpRequestBase = (HttpRequestBase) each;
                URIBuilder uriBuilder = new URIBuilder(httpRequestBase.getURI().toString());
                uriBuilder.addParameter(Constants.TRACE_ID, ctx.getTraceId());
                uriBuilder.addParameter(Constants.TRACE_PARENT_ID, ctx.getTraceStack().peek());
                httpRequestBase.setURI(uriBuilder.build());
                if (logger.isDebugEnabled()) {
                    logger.debug("add trace to http query parameters  : " + httpRequestBase.getURI().toString());
                }
                sign.set(true);
                try {
                    return method.invoke(bean, args);
                } finally {
                    sign.remove();
                }
            }
        }
    }
    return method.invoke(bean, args);
}
Example 42
Project: ironcache-master  File: ApacheHttpTransport.java View source code
/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.google.api.client.http.HttpTransport#buildRequest(java.lang.String,
	 * java.lang.String)
	 */
@Override
protected LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
    HttpRequestBase requestBase;
    if (method.equals(HttpMethods.DELETE)) {
        requestBase = new HttpDelete(url);
    } else if (method.equals(HttpMethods.GET)) {
        requestBase = new HttpGet(url);
    } else if (method.equals(HttpMethods.HEAD)) {
        requestBase = new HttpHead(url);
    } else if (method.equals(HttpMethods.POST)) {
        requestBase = new HttpPost(url);
    } else if (method.equals(HttpMethods.PUT)) {
        requestBase = new HttpPut(url);
    } else if (method.equals(HttpMethods.TRACE)) {
        requestBase = new HttpTrace(url);
    } else if (method.equals(HttpMethods.OPTIONS)) {
        requestBase = new HttpOptions(url);
    } else {
        requestBase = new HttpExtensionMethod(method, url);
    }
    return new ApacheHttpRequest(httpClient, requestBase);
}
Example 43
Project: OSRSHelper-master  File: HTTPRequest.java View source code
private void performRequest(String URL, RequestType requestType, Map<String, String> data) {
    statusCode = StatusCode.FOUND;
    HttpClient httpClient = new DefaultHttpClient();
    HttpRequestBase httpRequest;
    HttpResponse httpResponse;
    HttpEntity httpEntity;
    InputStream is = null;
    int statusCode = -1;
    try {
        if (requestType == RequestType.GET) {
            httpRequest = new HttpGet(URL);
        } else // assume POST
        {
            httpRequest = new HttpPost(URL);
        }
        httpResponse = httpClient.execute(httpRequest);
        httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();
        statusCode = httpResponse.getStatusLine().getStatusCode();
        this.statusCode = StatusCode.get(statusCode);
    } catch (HttpHostConnectException e) {
        e.printStackTrace();
    } catch (ConnectException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        output = sb.toString();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Example 44
Project: r2m-plugin-android-master  File: BaseRequest.java View source code
@Override
public void doWork() throws Exception {
    HttpClient httpClient = HttpClientBuilder.create().build();
    HttpRequestBase request = getRequest(requestModel);
    List<RequestHeaderModel> requestModelHeaders = requestModel.getHeaders();
    for (RequestHeaderModel header : requestModelHeaders) {
        request.setHeader(header.getName(), header.getValue());
    }
    // Add the header here so the request is successful.
    if (request.getHeaders(ContentTypeHelper.CONTENT_TYPE_HEADER) == null || request.getHeaders(ContentTypeHelper.CONTENT_TYPE_HEADER).length == 0) {
        RestContentType type = ExampleParser.guessContentType(requestModel.getRequest());
        if (null != type) {
            request.setHeader(ContentTypeHelper.CONTENT_TYPE_HEADER, type.getName());
        }
    }
    // check if content-type is parameterized
    HttpResponse httpResponse = httpClient.execute(request);
    ApiMethodModel methodModel = new ApiMethodModel();
    methodModel.setRequestHeaders(request.getAllHeaders());
    methodModel.setHttpResponse(httpResponse);
    methodModel.setRequestModel(requestModel);
    onSuccess(methodModel);
}
Example 45
Project: rest-assured-master  File: HttpRequestFactory.java View source code
/**
     * Get the HttpRequest class that represents this request type.
     *
     * @return a non-abstract class that implements {@link HttpRequest}
     */
static HttpRequestBase createHttpRequest(URI uri, String httpMethod) {
    String method = notNull(upperCase(trimToNull(httpMethod)), "Http method");
    Class<? extends HttpRequestBase> type = HTTP_METHOD_TO_HTTP_REQUEST_TYPE.get(method);
    final HttpRequestBase httpRequest;
    if (type == null) {
        httpRequest = new CustomHttpMethod(method, uri);
    } else {
        try {
            httpRequest = type.newInstance();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        httpRequest.setURI(uri);
    }
    return httpRequest;
}
Example 46
Project: Resteasy-master  File: ApacheHttpClient43Engine.java View source code
private RequestConfig getCurrentConfiguration(final ClientInvocation request, final HttpRequestBase httpMethod) {
    RequestConfig baseConfig;
    if (httpMethod != null && httpMethod.getConfig() != null) {
        baseConfig = httpMethod.getConfig();
    } else {
        ApacheHttpClient43Engine engine = ((ApacheHttpClient43Engine) request.getClient().httpEngine());
        baseConfig = ((Configurable) engine.getHttpClient()).getConfig();
        if (baseConfig == null) {
            Configurable clientConfiguration = (Configurable) httpClient;
            baseConfig = clientConfiguration.getConfig();
        }
    }
    return baseConfig;
}
Example 47
Project: Restlib-master  File: RestServiceCaller.java View source code
public RestResponse execute(RestRequest request) {
    final RestResponse response;
    try {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpRequestBase httpRequest = null;
        HttpEntityEnclosingRequestBase entityRequest;
        switch(request.getMethod()) {
            case RestRequest.GET_METHOD:
                httpRequest = new HttpGet(request.getURI());
                break;
            case RestRequest.POST_METHOD:
                httpRequest = new HttpPost(request.getURI());
                entityRequest = (HttpEntityEnclosingRequestBase) httpRequest;
                entityRequest.setEntity(new StringEntity(request.getContent()));
                break;
            case RestRequest.PUT_METHOD:
                httpRequest = new HttpPut(request.getURI());
                entityRequest = (HttpEntityEnclosingRequestBase) httpRequest;
                entityRequest.setEntity(new StringEntity(request.getContent()));
                break;
            case RestRequest.DELETE_METHOD:
                httpRequest = new HttpDelete(request.getURI());
                entityRequest = (HttpEntityEnclosingRequestBase) httpRequest;
                entityRequest.setEntity(new StringEntity(request.getContent()));
                break;
        }
        httpRequest.setHeader("Accept", "application/json");
        httpRequest.setHeader("Content-type", "application/json");
        response = new RestResponse();
        ResponseHandler<String> handler = new ResponseHandler<String>() {

            public String handleResponse(HttpResponse httpresponse) throws ClientProtocolException, IOException {
                StringBuilder r = new StringBuilder();
                BufferedReader reader = new BufferedReader(new InputStreamReader(httpresponse.getEntity().getContent(), "UTF-8"));
                for (String line = null; (line = reader.readLine()) != null; ) r.append(line).append("\n");
                response.setResponseCode(httpresponse.getStatusLine().getStatusCode());
                return r.toString();
            }
        };
        String result = httpclient.execute(httpRequest, handler);
        response.setResponse(result);
    } catch (Exception e) {
        return null;
    }
    return response;
}
Example 48
Project: sciencetoolkit-master  File: UploadRemoteAction.java View source code
@Override
public HttpRequestBase[] createRequests(String urlBase) {
    HttpPost post = new HttpPost(String.format("%sproject/%s/senseit/data", urlBase, projectId));
    MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
    ContentBody cbFile = new FileBody(series);
    entityBuilder.addTextBody("title", DataLogger.get().seriesName(profile, series), ContentType.TEXT_PLAIN);
    if (profile.getBool("requires_location")) {
        String location = DataLogger.get().getSeriesMetadata(profileId, series).getString("location");
        entityBuilder.addTextBody("geolocation", location);
    }
    entityBuilder.addPart("file", cbFile);
    HttpEntity entity = entityBuilder.build();
    post.setEntity(entity);
    return new HttpRequestBase[] { post };
}
Example 49
Project: streamsx.topology-master  File: Contexts.java View source code
static JSONObject getJsonResponse(CloseableHttpClient httpClient, HttpRequestBase request) throws IOException, ClientProtocolException {
    request.addHeader("accept", ContentType.APPLICATION_JSON.getMimeType());
    CloseableHttpResponse response = httpClient.execute(request);
    JSONObject jsonResponse;
    try {
        HttpEntity entity = response.getEntity();
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            final String errorInfo;
            if (entity != null)
                errorInfo = " -- " + EntityUtils.toString(entity);
            else
                errorInfo = "";
            throw new IllegalStateException("Unexpected HTTP resource from service:" + response.getStatusLine().getStatusCode() + ":" + response.getStatusLine().getReasonPhrase() + errorInfo);
        }
        if (entity == null)
            throw new IllegalStateException("No HTTP resource from service");
        jsonResponse = JSONObject.parse(new BufferedInputStream(entity.getContent()));
        EntityUtils.consume(entity);
    } finally {
        response.close();
    }
    return jsonResponse;
}
Example 50
Project: Tuit-ar-master  File: Avatar.java View source code
public void run() {
    DefaultHttpClient http = new DefaultHttpClient();
    HttpRequestBase request = new HttpGet(url);
    final HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, "UTF_8");
    HttpProtocolParams.setUseExpectContinue(params, false);
    http.setParams(params);
    try {
        HttpResponse response = http.execute(request);
        HttpEntity resEntity = response.getEntity();
        int statusCode = (response.getStatusLine().getStatusCode());
        if (resEntity != null && statusCode >= 200 && statusCode < 300) {
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            resEntity.writeTo(output);
            byte[] bytes = output.toByteArray();
            setResponse(BitmapFactory.decodeByteArray(bytes, 0, bytes.length));
        }
    } catch (Exception e) {
    }
    handler.post(runnable);
}
Example 51
Project: webpay-token-android-master  File: WebPayPublicClient.java View source code
/**
     * Send request to WebPay host
     * The caller should take care of exceptions
     * @param method        "GET" or "POST"
     * @param path          request path starts from /v*
     * @param jsonBody      json-format body string used only in "POST".
     * @return              pair of response code and body if request completed
     * @throws IOException
     */
Result request(String method, String path, String jsonBody) throws IOException {
    Uri.Builder builder = baseUri.buildUpon().appendEncodedPath(path);
    HttpRequestBase request;
    if (method.equals("GET")) {
        request = new HttpGet(builder.build().toString());
    } else if (method.equals("POST")) {
        HttpPost postRequest = new HttpPost(builder.build().toString());
        postRequest.setHeader("Content-Type", "application/json");
        postRequest.setEntity(new StringEntity(jsonBody, "UTF-8"));
        request = postRequest;
    } else {
        throw new IllegalArgumentException("method must be GET or POST");
    }
    request.setHeader("Accept-Language", language);
    request.setHeader("Authorization", "Bearer " + apiKey);
    request.setHeader("User-Agent", "WebPayTokenAndroid/" + BuildConfig.VERSION_NAME + " Android/" + Build.VERSION.RELEASE);
    DefaultHttpClient httpClient = new DefaultHttpClient();
    try {
        return httpClient.execute(request, new ResponseHandler<Result>() {

            @Override
            public Result handleResponse(HttpResponse response) throws IOException {
                int statusCode = response.getStatusLine().getStatusCode();
                String body = EntityUtils.toString(response.getEntity(), "UTF-8");
                return new Result(statusCode, body);
            }
        });
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}
Example 52
Project: Weikong-master  File: HttpConnection.java View source code
@SuppressWarnings("unchecked")
public static Map<String, String> requestJson(HttpRequestBase request) throws Exception {
    //创建HttpClientBuilder  
    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
    //HttpClient  
    CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
    HttpResponse httpResponse = closeableHttpClient.execute(request);
    //获��应消�实体  
    HttpEntity entity = httpResponse.getEntity();
    //判断�应实体是�为空  
    Map<String, String> map = new HashMap<String, String>();
    if (entity != null) {
        map = new ObjectMapper().readValue(EntityUtils.toString(entity), Map.class);
    }
    closeableHttpClient.close();
    return map;
}
Example 53
Project: android-discourse-master  File: BabayagaTask.java View source code
@Override
protected Void doInBackground(String... args) {
    try {
        JSONObject data = new JSONObject();
        if (traits != null && !traits.isEmpty()) {
            data.put("u", new JSONObject(traits));
        }
        if (eventProps != null && !eventProps.isEmpty()) {
            data.put("e", eventProps);
        }
        String subdomainId = Session.getInstance().getClientConfig().getSubdomainId();
        StringBuilder url = new StringBuilder(String.format("https://%s/t/%s/%s/%s", Babayaga.DOMAIN, subdomainId, Babayaga.CHANNEL, event));
        if (uvts != null) {
            url.append("/");
            url.append(uvts);
        }
        url.append("/track.js?_=");
        url.append(new Date().getTime());
        url.append("&c=_");
        if (data.length() != 0) {
            url.append("&d=");
            try {
                url.append(URLEncoder.encode(Base64.encodeToString(data.toString().getBytes(), Base64.NO_WRAP), "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
        }
        HttpRequestBase request = new HttpGet();
        request.setURI(new URI(url.toString()));
        AndroidHttpClient client = AndroidHttpClient.newInstance(String.format("uservoice-android-%s", UserVoice.getVersion()), Session.getInstance().getContext());
        HttpResponse response = client.execute(request);
        HttpEntity responseEntity = response.getEntity();
        StatusLine responseStatus = response.getStatusLine();
        int statusCode = responseStatus != null ? responseStatus.getStatusCode() : 0;
        if (statusCode != 200)
            return null;
        String body = responseEntity != null ? EntityUtils.toString(responseEntity) : null;
        client.close();
        if (body != null && !body.isEmpty()) {
            String payload = body.substring(2, body.length() - 2);
            JSONObject responseData = new JSONObject(payload);
            String uvts = responseData.getString("uvts");
            Babayaga.setUvts(uvts);
        }
    } catch (Exception e) {
        e.printStackTrace();
        Log.e("UV", String.format("%s: %s", e.getClass().getName(), e.getMessage()));
    }
    return null;
}
Example 54
Project: android-rackspacecloud-master  File: HttpBundle.java View source code
private String getCurl(HttpRequestBase message) {
    StringBuilder result = new StringBuilder("curl -verbose -X ");
    result.append(message.getMethod());
    HeaderIterator itr = message.headerIterator();
    while (itr.hasNext()) {
        Header header = itr.nextHeader();
        String key = header.getName();
        String value = header.getValue();
        /**/
        if (key.equals("X-Auth-Token") || key.equals("X-Auth-Key")) {
            value = "<secret>";
        }
        /**/
        result.append(" -H \"" + key + ": " + value + "\"");
    }
    /* no body for just HttpRequestBase
		HttpEntity entity = message.getEntity();
		String xmlBody = null;
		try {
			xmlBody = EntityUtils.toString(entity);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		if(xmlBody != null && !xmlBody.equals("")){
			result.append(" -d \"<?xml version=\"1.0\" encoding=\"UTF-8\"?> " + xmlBody + "\"");
		}
		*/
    result.append(" " + message.getURI());
    return result.toString();
}
Example 55
Project: aws-java-sdk-master  File: MockedClientTests.java View source code
@Test
public void requestTimeoutEnabled_RequestCompletesWithinTimeout_TaskCanceledAndEntityBuffered() throws Exception {
    ClientConfiguration config = new ClientConfiguration().withRequestTimeout(5 * 1000).withMaxErrorRetry(0);
    ConnectionManagerAwareHttpClient rawHttpClient = createRawHttpClientSpy(config);
    HttpResponseProxy responseProxy = createHttpResponseProxySpy();
    doReturn(responseProxy).when(rawHttpClient).execute(any(HttpRequestBase.class), any(HttpContext.class));
    httpClient = new AmazonHttpClient(config, rawHttpClient, null);
    try {
        execute(httpClient, createMockGetRequest());
        fail("Exception expected");
    } catch (AmazonClientException e) {
        NullResponseHandler.assertIsUnmarshallingException(e);
    }
    assertResponseIsBuffered(responseProxy);
    ScheduledThreadPoolExecutor requestTimerExecutor = httpClient.getHttpRequestTimer().getExecutor();
    assertTimerNeverTriggered(requestTimerExecutor);
    assertCanceledTasksRemoved(requestTimerExecutor);
    // Core threads should be spun up on demand. Since only one task was submitted only one
    // thread should exist
    assertEquals(1, requestTimerExecutor.getPoolSize());
    assertCoreThreadsShutDownAfterBeingIdle(requestTimerExecutor);
}
Example 56
Project: aws-sdk-java-master  File: MockedClientTests.java View source code
@Test
public void requestTimeoutEnabled_RequestCompletesWithinTimeout_TaskCanceledAndEntityBuffered() throws Exception {
    ClientConfiguration config = new ClientConfiguration().withRequestTimeout(5 * 1000).withMaxErrorRetry(0);
    ConnectionManagerAwareHttpClient rawHttpClient = createRawHttpClientSpy(config);
    HttpResponseProxy responseProxy = createHttpResponseProxySpy();
    doReturn(responseProxy).when(rawHttpClient).execute(any(HttpRequestBase.class), any(HttpContext.class));
    httpClient = new AmazonHttpClient(config, rawHttpClient, null);
    try {
        execute(httpClient, createMockGetRequest());
        fail("Exception expected");
    } catch (AmazonClientException e) {
        NullResponseHandler.assertIsUnmarshallingException(e);
    }
    assertResponseIsBuffered(responseProxy);
    ScheduledThreadPoolExecutor requestTimerExecutor = httpClient.getHttpRequestTimer().getExecutor();
    assertTimerNeverTriggered(requestTimerExecutor);
    assertCanceledTasksRemoved(requestTimerExecutor);
    // Core threads should be spun up on demand. Since only one task was submitted only one
    // thread should exist
    assertEquals(1, requestTimerExecutor.getPoolSize());
    assertCoreThreadsShutDownAfterBeingIdle(requestTimerExecutor);
}
Example 57
Project: blindr-master  File: HTTPRequest.java View source code
private void performRequest(String URL, RequestType requestType, List<NameValuePair> data, List<NameValuePair> headers) {
    statusCode = StatusCode.FOUND;
    HttpClient httpClient = new DefaultHttpClient();
    HttpRequestBase httpRequest;
    HttpResponse httpResponse;
    HttpEntity httpEntity;
    InputStream is = null;
    int statusCode = -1;
    try {
        if (requestType == RequestType.GET) {
            if (data != null) {
                URL += "?" + URLEncodedUtils.format(data, "utf-8");
            }
            HttpGet httpGet = new HttpGet(URL);
            httpRequest = httpGet;
        } else // assume POST
        {
            HttpPost httpPost = new HttpPost(URL);
            httpPost.setEntity(new UrlEncodedFormEntity(data));
            httpRequest = httpPost;
        }
        if (headers != null) {
            for (NameValuePair pair : headers) {
                httpRequest.addHeader(pair.getName(), pair.getValue());
            }
        }
        httpResponse = httpClient.execute(httpRequest);
        httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();
        statusCode = httpResponse.getStatusLine().getStatusCode();
        this.statusCode = StatusCode.get(statusCode);
    } catch (HttpHostConnectException e) {
        e.printStackTrace();
    } catch (ConnectException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        output = sb.toString();
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Example 58
Project: build-info-master  File: ArtifactoryXrayClient.java View source code
private ArtifactoryXrayResponse execute(HttpRequestBase httpRequest) throws InterruptedException, IOException {
    PreemptiveHttpClient client = httpClient.getHttpClient(XRAY_SCAN_CONNECTION_TIMEOUT_SECS);
    int retryNum = 0;
    long lastConnectionAttemptMillis = 0;
    while (true) {
        try {
            lastConnectionAttemptMillis = System.currentTimeMillis();
            retryNum++;
            HttpResponse response = client.execute(httpRequest);
            return parseXrayScanResponse(response);
        } catch (IOException e) {
            if (isStableConnection(lastConnectionAttemptMillis)) {
                retryNum = 0;
                continue;
            }
            if (XRAY_SCAN_RETRY_CONSECUTIVE_RETRIES <= retryNum) {
                throw e;
            }
            log.warn("Xray scan connection lost: " + e.getMessage() + ", attempting to reconnect...");
            Thread.sleep(XRAY_SCAN_SLEEP_BETWEEN_RETRIES_MILLIS);
        } finally {
            httpRequest.releaseConnection();
        }
    }
}
Example 59
Project: claudia-master  File: EnvironmentServerDeployerImpl.java View source code
/**
	 * {@inheritDoc}
	 */
@Override
public void deploy(Environment environment) throws EnvironmentDeploymentException {
    String vm_url = Constants.PROTOCOL + host + ":" + port + path + "/" + environment.getVmFqn();
    HttpRequestBase method = new HttpPost(vm_url);
    try {
        HttpEntity request = new StringEntity(environment.getContent());
        ((HttpPost) method).setEntity(request);
        method.setHeader("Content-Type", "application/xml");
        HttpResponse response = httpClient.execute(method);
        if (response.getStatusLine().getStatusCode() != 200)
            throw new EnvironmentDeploymentException("Remote HTTP Error code: " + response.getStatusLine().getStatusCode());
        log.info("Deploying context in " + vm_url);
    } catch (UnsupportedEncodingException e) {
        log.error(e.getMessage());
        throw new EnvironmentDeploymentException(e);
    } catch (ClientProtocolException e) {
        log.error(e.getMessage());
        throw new EnvironmentDeploymentException(e);
    } catch (IOException e) {
        log.error(e.getMessage());
        throw new EnvironmentDeploymentException(e);
    }
}
Example 60
Project: Connect-SDK-Android-Core-master  File: ServiceCommand.java View source code
public HttpRequestBase getRequest() {
    if (target == null) {
        throw new IllegalStateException("ServiceCommand has no target url");
    }
    if (this.httpMethod.equalsIgnoreCase(TYPE_GET)) {
        return new HttpGet(target);
    } else if (this.httpMethod.equalsIgnoreCase(TYPE_POST)) {
        return new HttpPost(target);
    } else if (this.httpMethod.equalsIgnoreCase(TYPE_DEL)) {
        return new HttpDelete(target);
    } else if (this.httpMethod.equalsIgnoreCase(TYPE_PUT)) {
        return new HttpPut(target);
    } else {
        return null;
    }
}
Example 61
Project: desktopclient-java-master  File: HKPClient.java View source code
public String search(String server, String keyID) {
    CloseableHttpClient client = HttpClients.createDefault();
    HttpRequestBase get = new HttpGet("https://" + server + "/pks/lookup?op=get&options=mr&exact=on&search=0x" + keyID);
    // execute request
    CloseableHttpResponse response;
    try {
        response = client.execute(get);
    } catch (IOException ex) {
        LOGGER.log(Level.WARNING, "can't execute request, server: " + server, ex);
        return "";
    }
    try {
        int code = response.getStatusLine().getStatusCode();
        if (code != HttpStatus.SC_OK) {
            if (code == HttpStatus.SC_NOT_FOUND) {
                LOGGER.config("key not found, server: " + server + "; keyID=" + keyID);
            } else {
                LOGGER.warning("unexpected response, server: " + server + "; code=" + code);
            }
            return "";
        }
        HttpEntity entity = response.getEntity();
        if (entity == null) {
            LOGGER.warning("no download response entity");
            return "";
        }
        if (entity.getContentLength() > MAX_CONTENT_LENGTH) {
            LOGGER.warning("content too big");
            return "";
        }
        String contentStr;
        try {
            contentStr = IOUtils.toString(entity.getContent(), "UTF-8");
        } catch (IOExceptionIllegalStateException |  ex) {
            LOGGER.log(Level.WARNING, " can't read content", ex);
            return "";
        }
        return contentStr;
    } finally {
        try {
            response.close();
        } catch (IOException ex) {
            LOGGER.log(Level.WARNING, "can't close response", ex);
        }
    }
}
Example 62
Project: elmis-master  File: SeleniumFileDownloadUtil.java View source code
private HttpResponse getHTTPResponse() throws IOException, NullPointerException {
    if (fileURI == null)
        throw new NullPointerException("No file URI specified");
    HttpClient client = new DefaultHttpClient();
    BasicHttpContext localContext = new BasicHttpContext();
    //Clear down the local cookie store every time to make sure we don't have any left over cookies influencing the test
    localContext.setAttribute(ClientContext.COOKIE_STORE, null);
    //Mimic WebDriver cookie state
    localContext.setAttribute(ClientContext.COOKIE_STORE, getCurrentCookieStoreState());
    HttpRequestBase requestMethod = new HttpGet();
    requestMethod.setURI(fileURI);
    HttpParams httpRequestParameters = requestMethod.getParams();
    httpRequestParameters.setParameter(ClientPNames.HANDLE_REDIRECTS, Boolean.TRUE);
    requestMethod.setParams(httpRequestParameters);
    return client.execute(requestMethod, localContext);
}
Example 63
Project: fanfouapp-opensource-master  File: SimpleClient.java View source code
private final HttpResponse executeImpl(final HttpRequestBase request) throws IOException {
    if (request == null) {
        throw new IOException("http request is null");
    }
    final HttpClient client = getHttpClient();
    if (AppContext.DEBUG) {
        Log.d(SimpleClient.TAG, "[Request] " + request.getRequestLine().toString());
    }
    final HttpResponse response = client.execute(request);
    if (AppContext.DEBUG) {
        Log.d(SimpleClient.TAG, "[Response] " + response.getStatusLine().toString());
    }
    return response;
}
Example 64
Project: foursquared-dz-master  File: HttpApiWithOAuth.java View source code
public FoursquareType doHttpRequest(HttpRequestBase httpRequest, Parser<? extends FoursquareType> parser) throws FoursquareCredentialsException, FoursquareParseException, FoursquareException, IOException {
    if (DEBUG)
        LOG.log(Level.FINE, "doHttpRequest: " + httpRequest.getURI());
    try {
        if (DEBUG)
            LOG.log(Level.FINE, "Signing request: " + httpRequest.getURI());
        if (DEBUG)
            LOG.log(Level.FINE, "Consumer: " + mConsumer.getConsumerKey() + ", " + mConsumer.getConsumerSecret());
        if (DEBUG)
            LOG.log(Level.FINE, "Token: " + mConsumer.getToken() + ", " + mConsumer.getTokenSecret());
        mConsumer.sign(httpRequest);
    } catch (OAuthMessageSignerException e) {
        if (DEBUG)
            LOG.log(Level.FINE, "OAuthMessageSignerException", e);
        throw new RuntimeException(e);
    } catch (OAuthExpectationFailedException e) {
        if (DEBUG)
            LOG.log(Level.FINE, "OAuthExpectationFailedException", e);
        throw new RuntimeException(e);
    }
    return executeHttpRequest(httpRequest, parser);
}
Example 65
Project: foursquared-master  File: HttpApiWithOAuth.java View source code
public FoursquareType doHttpRequest(HttpRequestBase httpRequest, Parser<? extends FoursquareType> parser) throws FoursquareCredentialsException, FoursquareParseException, FoursquareException, IOException {
    if (DEBUG)
        LOG.log(Level.FINE, "doHttpRequest: " + httpRequest.getURI());
    try {
        if (DEBUG)
            LOG.log(Level.FINE, "Signing request: " + httpRequest.getURI());
        if (DEBUG)
            LOG.log(Level.FINE, "Consumer: " + mConsumer.getConsumerKey() + ", " + mConsumer.getConsumerSecret());
        if (DEBUG)
            LOG.log(Level.FINE, "Token: " + mConsumer.getToken() + ", " + mConsumer.getTokenSecret());
        mConsumer.sign(httpRequest);
    } catch (OAuthMessageSignerException e) {
        if (DEBUG)
            LOG.log(Level.FINE, "OAuthMessageSignerException", e);
        throw new RuntimeException(e);
    } catch (OAuthExpectationFailedException e) {
        if (DEBUG)
            LOG.log(Level.FINE, "OAuthExpectationFailedException", e);
        throw new RuntimeException(e);
    }
    return executeHttpRequest(httpRequest, parser);
}
Example 66
Project: geomajas-project-client-gwt-master  File: GwtProxyController.java View source code
@RequestMapping(value = "/")
public final void proxyAjaxCall(@RequestParam(required = true, value = "url") String url, HttpServletRequest request, HttpServletResponse response) throws IOException {
    // URL needs to be url decoded
    url = URLDecoder.decode(url, "utf-8");
    HttpClient client = new DefaultHttpClient();
    try {
        HttpRequestBase proxyRequest;
        // Split this according to the type of request
        if ("GET".equals(request.getMethod())) {
            Enumeration<?> paramNames = request.getParameterNames();
            while (paramNames.hasMoreElements()) {
                String paramName = (String) paramNames.nextElement();
                if (!paramName.equalsIgnoreCase("url")) {
                    url = addParam(url, paramName, request.getParameter(paramName));
                }
            }
            proxyRequest = new HttpGet(url);
        } else if ("POST".equals(request.getMethod())) {
            proxyRequest = new HttpPost(url);
            // Set any eventual parameters that came with our original
            HttpParams params = new BasicHttpParams();
            Enumeration<?> paramNames = request.getParameterNames();
            while (paramNames.hasMoreElements()) {
                String paramName = (String) paramNames.nextElement();
                if (!"url".equalsIgnoreCase("url")) {
                    params.setParameter(paramName, request.getParameter(paramName));
                }
            }
            proxyRequest.setParams(params);
        } else {
            throw new NotImplementedException("This proxy only supports GET and POST methods.");
        }
        // Execute the method
        HttpResponse proxyResponse = client.execute(proxyRequest);
        // Set the content type, as it comes from the server
        Header[] headers = proxyResponse.getAllHeaders();
        for (Header header : headers) {
            if ("Content-Type".equalsIgnoreCase(header.getName())) {
                response.setContentType(header.getValue());
            }
        }
        // Write the body, flush and close
        proxyResponse.getEntity().writeTo(response.getOutputStream());
    } catch (IOException e) {
        e.printStackTrace();
        throw e;
    }
}
Example 67
Project: geomajas-project-client-gwt2-master  File: AjaxProxyController.java View source code
@RequestMapping(value = "/")
public final void proxyAjaxCall(@RequestParam(required = true, value = "url") String url, HttpServletRequest request, HttpServletResponse response) throws IOException {
    // URL needs to be url decoded
    url = URLDecoder.decode(url, "utf-8");
    HttpClient client = new DefaultHttpClient();
    try {
        HttpRequestBase proxyRequest;
        // Split this according to the type of request
        if ("GET".equals(request.getMethod())) {
            Enumeration<?> paramNames = request.getParameterNames();
            while (paramNames.hasMoreElements()) {
                String paramName = (String) paramNames.nextElement();
                if (!paramName.equalsIgnoreCase("url")) {
                    url = addParam(url, paramName, request.getParameter(paramName));
                }
            }
            proxyRequest = new HttpGet(url);
        } else if ("POST".equals(request.getMethod())) {
            proxyRequest = new HttpPost(url);
            // Set any eventual parameters that came with our original
            HttpParams params = new BasicHttpParams();
            Enumeration<?> paramNames = request.getParameterNames();
            while (paramNames.hasMoreElements()) {
                String paramName = (String) paramNames.nextElement();
                if (!"url".equalsIgnoreCase("url")) {
                    params.setParameter(paramName, request.getParameter(paramName));
                }
            }
            proxyRequest.setParams(params);
        } else {
            throw new NotImplementedException("This proxy only supports GET and POST methods.");
        }
        // Execute the method
        HttpResponse proxyResponse = client.execute(proxyRequest);
        // Set the content type, as it comes from the server
        Header[] headers = proxyResponse.getAllHeaders();
        for (Header header : headers) {
            if ("Content-Type".equalsIgnoreCase(header.getName())) {
                response.setContentType(header.getValue());
            }
        }
        // Write the body, flush and close
        proxyResponse.getEntity().writeTo(response.getOutputStream());
    } catch (IOException e) {
        e.printStackTrace();
        throw e;
    }
}
Example 68
Project: GeoRedTSI2-master  File: ServicioRest.java View source code
protected static HttpResponse rest(Metodos metodo, String url, String content, Boolean secure) {
    try {
        HttpRequestBase request = null;
        switch(metodo) {
            case GET:
                {
                    request = new HttpGet(url);
                }
                break;
            case POST:
                {
                    request = new HttpPost(url);
                    if (content != null) {
                        StringEntity entry = new StringEntity(content);
                        entry.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
                        ((HttpPost) request).setEntity(entry);
                    }
                }
                break;
            case PUT:
                {
                    request = new HttpPut(url);
                    if (content != null) {
                        StringEntity entry = new StringEntity(content);
                        entry.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
                        ((HttpPut) request).setEntity(entry);
                    }
                }
                break;
        }
        if (request != null) {
            if (secure)
                request.addHeader(SECURITY_HEADER, getSecurityToken());
            HttpClient cliente = new DefaultHttpClient();
            HttpResponse response = cliente.execute(request, new BasicHttpContext());
            return response;
        } else {
            Log.d("Error", "Request mal formado.");
            return null;
        }
    } catch (ClientProtocolException e) {
        Log.e("Error", "URI syntax was incorrect.", e);
        e.printStackTrace();
    } catch (IOException e) {
        Log.e("Error", "There was a problem when sending the request.", e);
        e.printStackTrace();
    }
    return null;
}
Example 69
Project: http-queue-master  File: HttpRequestMessage.java View source code
public void send() {
    HttpClientBuilder httpClientBuilder = HttpClients.custom();
    if (useBasicAuth) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(new AuthScope("localhost", 443), new UsernamePasswordCredentials(username, password));
        httpClientBuilder = httpClientBuilder.setDefaultCredentialsProvider(credsProvider);
    }
    try (CloseableHttpClient httpClient = httpClientBuilder.build()) {
        HttpRequestBase http = null;
        if ("GET".equalsIgnoreCase(method)) {
            http = new HttpGet(url);
        } else if ("POST".equalsIgnoreCase(method)) {
            http = new HttpPost(url);
        } else if ("PUT".equalsIgnoreCase(method)) {
            http = new HttpPut(url);
        } else if ("DELETE".equalsIgnoreCase(method)) {
            http = new HttpDelete(url);
        } else {
            throw new RuntimeException("Unsupported HTTP method exception : " + method);
        }
        if (useCookie) {
            http.setHeader("Cookie", cookieName + "=" + cookieContent);
        }
        Stopwatch stopwatch = Stopwatch.createStarted();
        try (CloseableHttpResponse response = httpClient.execute(http)) {
            responseStatus = response.getStatusLine().getStatusCode();
            responseContent = EntityUtils.toString(response.getEntity());
            stopwatch.stop();
            if (success()) {
                logger.info("Message to {} processed successfully with code {} [{} ms]", url, responseStatus, stopwatch.elapsed(TimeUnit.MILLISECONDS));
            } else {
                logger.info("Request to {} processed with error code {} [{} ms] : \n{}", url, responseStatus, stopwatch.elapsed(TimeUnit.MILLISECONDS), responseContent);
            }
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
Example 70
Project: Inside_Android_Testing-master  File: Http.java View source code
private Response makeRequest(Map<String, String> headers, String username, String password, HttpRequestBase method, String host) {
    try {
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            method.setHeader(entry.getKey(), entry.getValue());
        }
        DefaultHttpClient client = getHttpClient();
        addBasicAuthCredentials(client, host, username, password);
        return new Response(client.execute(method));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
Example 71
Project: j-google-trends-api-master  File: GoogleTrendsClient.java View source code
/**
   * Execute the request.
   *
   * @param request
   * @return content The content of the response
   * @throws GoogleTrendsClientException
   */
public String execute(GoogleTrendsRequest request) throws GoogleTrendsClientException {
    String html = null;
    try {
        if (!authenticator.isLoggedIn()) {
            authenticator.authenticate();
        }
        Logger.getLogger(GoogleConfigurator.getLoggerPrefix()).log(Level.FINE, "Query: {0}", request.build().toString());
        HttpRequestBase httpRequest = request.build();
        HttpResponse response = client.execute(httpRequest);
        html = GoogleUtils.toString(response.getEntity().getContent());
        httpRequest.releaseConnection();
        Pattern p = Pattern.compile(GoogleConfigurator.getConfiguration().getString("google.trends.client.reError"), Pattern.CASE_INSENSITIVE);
        Matcher matcher = p.matcher(html);
        if (matcher.find()) {
            throw new GoogleTrendsClientException("*** You are running too fast man! Looks like you reached your quota limit. Wait a while and slow it down with the '-S' option! *** ");
        }
    } catch (GoogleAuthenticatorException ex) {
        throw new GoogleTrendsClientException(ex);
    } catch (ClientProtocolException ex) {
        throw new GoogleTrendsClientException(ex);
    } catch (IOException ex) {
        throw new GoogleTrendsClientException(ex);
    } catch (ConfigurationException ex) {
        throw new GoogleTrendsClientException(ex);
    } catch (GoogleTrendsRequestException ex) {
        throw new GoogleTrendsClientException(ex);
    }
    return html;
}
Example 72
Project: jframe-master  File: TestHttpClientService.java View source code
public void testJson() {
    try {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpHost target = new HttpHost("120.27.182.142", 80, HttpHost.DEFAULT_SCHEME_NAME);
        HttpRequestBase request = new HttpPost(target.toURI() + "/mry/usr/qryusr");
        request.addHeader("Api-Token", "76067");
        String data = "";
        // ((HttpPost) request).setEntity(new StringEntity(data,
        // ContentType.create("text/plain", "utf-8")));
        CloseableHttpResponse resp = httpClient.execute(request);
        HttpEntity entity = resp.getEntity();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        InputStream is = entity.getContent();
        byte[] buf = new byte[32];
        int len = 0;
        while ((len = is.read(buf)) != -1) {
            baos.write(buf, 0, len);
        }
        String str = new String(baos.toByteArray(), "utf-8");
        for (byte b : baos.toByteArray()) {
            System.out.print(b);
            System.out.print(' ');
        }
        Reader reader = new InputStreamReader(entity.getContent(), ContentType.getOrDefault(entity).getCharset());
        // TODO decode by mime-type
        Map<String, String> rspMap = GSON.fromJson(reader, HashMap.class);
        String usrJson = rspMap.get("usr");
        Map<String, Object> usr = GSON.fromJson(usrJson, HashMap.class);
        System.out.println(usr.get("id").toString() + usr.get("name"));
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Example 73
Project: MapAttack-Android-master  File: MyRequest.java View source code
public synchronized HttpRequestBase getRequest() {
    ADB.log("------------------------------------------");
    ADB.log("URI: " + request.getURI());
    for (Header header : headers) {
        ADB.log("Header: " + header.getName() + "=" + header.getValue());
    }
    ADB.log("Parameters: " + params.toString());
    for (BasicNameValuePair param : entityParams) {
        ADB.log("Entity Parameter: " + param.getName() + "=" + param.getValue());
    }
    //Set headers
    if (headers.size() > 0) {
        request.setHeaders(headers.toArray(new Header[headers.size()]));
    }
    //Set params
    request.setParams(params);
    //Set entity
    if (request instanceof HttpEntityEnclosingRequestBase) {
        if (entityParams.size() > 0) {
            if (entity != null) {
                throw new RuntimeException("Entity conflict");
            } else {
                try {
                    ((HttpEntityEnclosingRequestBase) request).setEntity(new UrlEncodedFormEntity(entityParams));
                } catch (UnsupportedEncodingException e) {
                    throw new RuntimeException(e.getMessage());
                }
            }
        } else if (entity != null) {
            ((HttpEntityEnclosingRequestBase) request).setEntity(entity);
        }
    }
    return request;
}
Example 74
Project: mdk-master  File: ImageValidator.java View source code
public void validate(Project project) {
    for (String key : images.keySet()) {
        // customize request
        URIBuilder requestUri = MMSUtils.getServiceProjectsRefsElementsUri(project);
        if (requestUri == null) {
            return;
        }
        Element e = Converters.getIdToElementConverter().apply(key, project);
        String id = key.replace(".", "%2E");
        requestUri.setPath(requestUri.getPath() + "/" + id);
        JsonNode value;
        String cs = "";
        if ((value = images.get(key).get("cs")) != null && value.isTextual()) {
            cs = value.asText();
        }
        requestUri.setParameter("cs", cs);
        String extension = "svg";
        if ((value = images.get(key).get("extension")) != null && value.isTextual()) {
            extension = value.asText();
        }
        requestUri.setParameter("extension", extension);
        File responseFile;
        ObjectNode response;
        // do request
        try {
            HttpRequestBase request = MMSUtils.buildRequest(MMSUtils.HttpRequestType.GET, requestUri);
            request.setHeader("Accept", "image/" + extension);
            responseFile = MMSUtils.sendMMSRequest(project, request);
            try (JsonParser responseParser = JacksonUtils.getJsonFactory().createParser(responseFile)) {
                response = JacksonUtils.parseJsonObject(responseParser);
                if (((value = response.get("message")) == null || !value.isTextual() || value.asText().contains("not found")) || ((value = response.get("cs")) == null || !value.isTextual() || !value.asText().equals(cs))) {
                    ValidationRuleViolation v = new ValidationRuleViolation(e, "[IMAGE] This image is outdated on the web.");
                    v.addAction(new ExportImage(e, allImages));
                    rule.addViolation(v);
                }
            }
        } catch (ServerExceptionIOException | URISyntaxException |  e1) {
            Application.getInstance().getGUILog().log("[ERROR] Exception occurred while validating image " + key + ". Image validation cancelled. Reason: " + e1.getMessage());
            e1.printStackTrace();
            continue;
        }
    }
}
Example 75
Project: MOCBuilder-master  File: BrickLinkClient.java View source code
public <T extends Response<?>> T execute(Request<T> request) throws Exception {
    String url = BASE_URL + request.getPath();
    HttpRequestBase httpRequest = new HttpGet(addQueryParams2URL(url, getGETParameter(request)));
    consumer.sign(httpRequest);
    CloseableHttpResponse httpResponse = client.execute(httpRequest);
    final T response;
    try {
        Parser<? extends T, ?> parser = request.getParser();
        String body = Parser.checkResponse(httpResponse);
        response = parser.parse(body);
    } finally {
        httpResponse.close();
    }
    return response;
}
Example 76
Project: mock-http-server-master  File: ApacheHttpClientImpl.java View source code
private HttpClientResponse<InputStream> execute(final HttpRequestBase request) throws IOException {
    final org.apache.http.client.HttpClient client = getClient();
    try {
        final HttpResponse httpResponse = client.execute(request);
        return buildResponse(client, httpResponse);
    } catch (final IOException e) {
        client.getConnectionManager().shutdown();
        throw e;
    }
}
Example 77
Project: moco-master  File: MocoRequestAction.java View source code
private void doExecute(final CloseableHttpClient client, final Request request) throws IOException {
    HttpRequestBase targetRequest = createRequest(url, method, request);
    if (targetRequest instanceof HttpEntityEnclosingRequest && content.isPresent()) {
        ((HttpEntityEnclosingRequest) targetRequest).setEntity(asEntity(content.get(), request));
    }
    client.execute(targetRequest);
}
Example 78
Project: mylyn.commons-master  File: CommonHttpOperation.java View source code
public CommonHttpResponse execute(HttpRequestBase request, IOperationMonitor monitor) throws IOException {
    monitor = OperationUtil.convert(monitor);
    // first attempt
    boolean requestCredentials;
    try {
        return executeOnce(request, monitor);
    } catch (AuthenticationException e) {
        requestCredentials = !e.shouldRetry();
        handleAuthenticationError(request, e, monitor, requestCredentials);
    }
    // second attempt
    try {
        return executeOnce(request, monitor);
    } catch (AuthenticationException e) {
        if (requestCredentials) {
            invalidateAuthentication(e, monitor);
            throw e;
        }
        handleAuthenticationError(request, e, monitor, true);
    }
    // third attempt
    return executeOnce(request, monitor);
}
Example 79
Project: oauth2-client4j-master  File: HttpClient4.java View source code
public <T extends OAuthResponse> T execute(Request request, Class<T> responseClass) {
    try {
        URI location = new URI(request.getLocationUri());
        HttpRequestBase req = null;
        if (!OAuthKit.isEmpty(request.getRequestType()) && OAuth.HttpMethod.POST.equals(request.getRequestType())) {
            List<NameValuePair> formparams = new ArrayList<NameValuePair>();
            for (Map.Entry<String, String> body : request.getBodyNameValuePair().entrySet()) {
                formparams.add(new BasicNameValuePair(body.getKey(), body.getValue()));
            }
            HttpEntity entity = new UrlEncodedFormEntity(formparams, Consts.UTF_8);
            req = new HttpPost(location);
            ((HttpPost) req).setEntity(entity);
        } else {
            req = new HttpGet(location);
        }
        if (request.getHeaders() != null) {
            for (Map.Entry<String, String> header : request.getHeaders().entrySet()) {
                req.setHeader(header.getKey(), header.getValue());
            }
        }
        HttpResponse response = client.execute(req);
        Header contentTypeHeader = null;
        Header encodingHeader = null;
        String responseBody = "";
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            responseBody = EntityUtils.toString(entity);
            contentTypeHeader = entity.getContentType();
            encodingHeader = entity.getContentEncoding();
        }
        String contentType = null;
        String characterEncoding = null;
        if (contentTypeHeader != null) {
            contentType = contentTypeHeader.toString();
        }
        if (encodingHeader != null) {
            characterEncoding = encodingHeader.toString();
        }
        return OAuthKit.createCustomResponse(responseBody, contentType, characterEncoding, response.getStatusLine().getStatusCode(), responseClass);
    } catch (URISyntaxException e) {
        throw new OAuthException(e);
    } catch (ClientProtocolException e) {
        throw new OAuthException(e);
    } catch (IOException e) {
        throw new OAuthException(e);
    }
}
Example 80
Project: opensource-master  File: SimpleClient.java View source code
private final HttpResponse executeImpl(final HttpRequestBase request) throws IOException {
    if (request == null) {
        throw new IOException("http request is null");
    }
    final HttpClient client = getHttpClient();
    if (AppContext.DEBUG) {
        Log.d(SimpleClient.TAG, "[Request] " + request.getRequestLine().toString());
    }
    final HttpResponse response = client.execute(request);
    if (AppContext.DEBUG) {
        Log.d(SimpleClient.TAG, "[Response] " + response.getStatusLine().toString());
    }
    return response;
}
Example 81
Project: pdfcombinercco-master  File: FileUploader.java View source code
/**
     * A generic method to execute any type of Http Request and constructs a response object
     * @param requestBase the request that needs to be exeuted
     * @return server response as <code>String</code>
     */
private static String executeRequest(HttpRequestBase requestBase) {
    String responseString = "";
    InputStream responseStream = null;
    HttpClient client = new DefaultHttpClient();
    try {
        HttpResponse response = client.execute(requestBase);
        if (response != null) {
            HttpEntity responseEntity = response.getEntity();
            if (responseEntity != null) {
                responseStream = responseEntity.getContent();
                if (responseStream != null) {
                    BufferedReader br = new BufferedReader(new InputStreamReader(responseStream));
                    String responseLine = br.readLine();
                    String tempResponseString = "";
                    while (responseLine != null) {
                        tempResponseString = tempResponseString + responseLine + System.getProperty("line.separator");
                        responseLine = br.readLine();
                    }
                    br.close();
                    if (tempResponseString.length() > 0) {
                        responseString = tempResponseString;
                    }
                }
            }
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (responseStream != null) {
            try {
                responseStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    client.getConnectionManager().shutdown();
    return responseString;
}
Example 82
Project: PennMeet-master  File: RESTClient.java View source code
public HttpResponse makeRequest(int type, String uri, String data) throws ClientProtocolException, IOException {
    HttpRequestBase request = null;
    switch(type) {
        case GET:
            request = new HttpGet(uri);
            break;
        case POST:
            request = new HttpPost(uri);
            break;
        case PUT:
            request = new HttpPut(uri);
            break;
        case DELETE:
            request = new HttpDelete(uri);
            break;
        default:
            throw new RuntimeException("Invalid HTTP request type: " + type);
    }
    if (headers != null) {
        for (Entry<String, String> header : headers.entrySet()) {
            request.setHeader(header.getKey(), header.getValue());
        }
    }
    if (data != null) {
        try {
            if (request instanceof HttpPut)
                ((HttpPut) request).setEntity(new StringEntity(data, "UTF-8"));
            if (request instanceof HttpPost)
                ((HttpPost) request).setEntity(new StringEntity(data, "UTF-8"));
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
    }
    HttpClient client = new DefaultHttpClient();
    System.out.println("Making " + request.getMethod() + " request to: " + uri);
    HttpResponse httpResponse = client.execute(request);
    this.response = httpResponse;
    return httpResponse;
}
Example 83
Project: popcorn-android-master  File: ServiceCommand.java View source code
public HttpRequestBase getRequest() {
    if (target == null) {
        throw new IllegalStateException("ServiceCommand has no target url");
    }
    if (this.httpMethod.equalsIgnoreCase(TYPE_GET)) {
        return new HttpGet(target);
    } else if (this.httpMethod.equalsIgnoreCase(TYPE_POST)) {
        return new HttpPost(target);
    } else if (this.httpMethod.equalsIgnoreCase(TYPE_DEL)) {
        return new HttpDelete(target);
    } else if (this.httpMethod.equalsIgnoreCase(TYPE_PUT)) {
        return new HttpPut(target);
    } else {
        return null;
    }
}
Example 84
Project: rhex-test-master  File: DocNotFoundDelete.java View source code
protected void validateResponse(HttpRequestBase req, HttpResponse response) throws TestException {
    int code = response.getStatusLine().getStatusCode();
    boolean success = code == 404 || code == 405;
    if (!success || log.isDebugEnabled()) {
        dumpResponse(req, response, true);
    }
    /*
		server responds with 404 code but HTML content shows an error so may not be handled correctly:

		<h1>Routing Error</h1>
		<p><pre>No route matches [DELETE] "/records/1/medications/should_not_exist"</pre></p>
		<p>
		  Try running <code>rake routes</code> for more information on available routes.
		</p>
		 */
    if (!success) {
        fail("Expected 404/405 status code but was " + code);
    }
}
Example 85
Project: RobolectricSample-master  File: Http.java View source code
private Response makeRequest(Map<String, String> headers, String username, String password, HttpRequestBase method, String host) {
    DefaultHttpClient client = null;
    try {
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            method.setHeader(entry.getKey(), entry.getValue());
        }
        client = getPromiscuousDefaultClient();
        addBasicAuthCredentials(client, host, username, password);
        return new Response(client.execute(method));
    } catch (IOException e) {
        throw new RuntimeException(e);
    } finally {
        if (client != null) {
            try {
                client.getConnectionManager().shutdown();
            } catch (Exception ignored) {
            }
        }
    }
}
Example 86
Project: selendroid-master  File: HttpClientUtil.java View source code
public static HttpResponse executeRequest(String url, HttpMethod method) throws Exception {
    HttpRequestBase request;
    if (HttpMethod.GET.equals(method)) {
        request = new HttpGet(url);
    } else if (HttpMethod.POST.equals(method)) {
        request = new HttpPost(url);
    } else if (HttpMethod.DELETE.equals(method)) {
        request = new HttpDelete(url);
    } else {
        throw new RuntimeException("Provided HttpMethod not supported: " + method);
    }
    return getHttpClient().execute(request);
}
Example 87
Project: skandroid-core-master  File: NetAction.java View source code
public void execute() {
    HttpParams httpParameters = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters, SKConstants.CONNECTION_TIMEOUT_30_SECONDS_IN_MILLIS);
    HttpConnectionParams.setSoTimeout(httpParameters, SKConstants.CONNECTION_TIMEOUT_30_SECONDS_IN_MILLIS);
    HttpClient httpclient = new DefaultHttpClient(httpParameters);
    HttpRequestBase mess = null;
    if (isPost) {
        mess = new HttpPost(request);
        if (body != null) {
            try {
                ((HttpPost) mess).setEntity(new StringEntity(body));
            } catch (UnsupportedEncodingException e) {
                SKPorting.sAssertE(this, "error creating http message", e);
            }
        }
    } else {
        mess = new HttpGet(request);
    }
    mess.setParams(params);
    for (Header h : headers) {
        mess.addHeader(h);
    }
    try {
        Log.d(TAG, "net request: " + request);
        response = httpclient.execute(mess);
    } catch (Exception e) {
        Log.e("NetAction", "failed to execute request: " + request + ", exception=" + e.toString());
        SKPorting.sAssert(getClass(), false);
    }
    if (isResponseOk()) {
        onActionFinished();
    } else if (response != null && response.getStatusLine() != null) {
        isSuccess = false;
        SKPorting.sAssertE(this, "failed request, response code: " + response.getStatusLine().getStatusCode());
        try {
            InputStream content = response.getEntity().getContent();
            List<String> lines = IOUtils.readLines(content);
            errorString = "";
            for (String s : lines) {
                errorString += "\n" + s;
            }
        } catch (Exception e) {
            SKPorting.sAssert(false);
        }
        SKPorting.sAssertE(this, errorString);
    }
}
Example 88
Project: small_video-master  File: HttpHelper.java View source code
private static HttpResult execute(String url, HttpRequestBase requestBase) {
    boolean isHttps = url.startsWith("https://");
    AbstractHttpClient httpClient = HttpClientFactory.create(isHttps);
    HttpContext httpContext = new SyncBasicHttpContext(new BasicHttpContext());
    HttpRequestRetryHandler retryHandler = httpClient.getHttpRequestRetryHandler();
    int retryCount = 0;
    boolean retry = true;
    while (retry) {
        try {
            HttpResponse response = httpClient.execute(requestBase, httpContext);
            if (response != null) {
                return new HttpResult(response, httpClient, requestBase);
            }
        } catch (Exception e) {
            IOException ioException = new IOException(e.getMessage());
            retry = retryHandler.retryRequest(ioException, ++retryCount, httpContext);
            e.printStackTrace();
        }
    }
    return null;
}
Example 89
Project: statsd-jvm-profiler-master  File: ProfilerServerTest.java View source code
private void httpRequestTest(String path, String expectedBody) throws IOException {
    HttpRequestBase get = new HttpGet(String.format("http://localhost:%d/%s", port, path));
    CloseableHttpResponse response = client.execute(get);
    int statusCode = response.getStatusLine().getStatusCode();
    assertEquals(200, statusCode);
    HttpEntity entity = response.getEntity();
    assertNotNull(entity);
    String responseBody = EntityUtils.toString(entity);
    assertEquals(expectedBody, responseBody);
    response.close();
}
Example 90
Project: stem-master  File: BaseHttpClient.java View source code
public <T extends StemResponse> T send(HttpRequestBase request, Class<T> clazz) {
    try {
        setHeaders(request);
        return (T) client.execute(request, getResponseHandler(clazz));
    } catch (HttpHostConnectException e) {
        throw new RuntimeException("Failed to connect to cluster manager", e);
    } catch (Exception e) {
        throw new RuntimeException("Unexpected error while sending request to cluster manager", e);
    }
}
Example 91
Project: weixin-mp-java-master  File: WxUtil.java View source code
@SuppressWarnings("unchecked")
public static final <T> T sendRequest(String url, HttpMethod method, Map<String, String> params, HttpEntity requestEntity, Class<T> resultClass) throws WxException {
    HttpClient client = HttpClientBuilder.create().build();
    HttpRequestBase request = null;
    try {
        if (HttpMethod.GET.equals(method)) {
            request = new HttpGet();
        } else if (HttpMethod.POST.equals(method)) {
            request = new HttpPost();
            if (requestEntity != null) {
                ((HttpPost) request).setEntity(requestEntity);
            }
        }
        URIBuilder builder = new URIBuilder(url);
        if (params != null) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                builder.addParameter(entry.getKey(), entry.getValue());
            }
        }
        request.setURI(builder.build());
        HttpResponse response = client.execute(request);
        HttpEntity entity = response.getEntity();
        String respBody = EntityUtils.toString(entity);
        if (entity != null) {
            EntityUtils.consume(entity);
        }
        if (String.class.isAssignableFrom(resultClass)) {
            return (T) respBody;
        } else {
            Gson gson = new Gson();
            if (respBody.indexOf("{\"errcode\"") == 0 || respBody.indexOf("{\"errmsg\"") == 0) {
                WxRespCode exJson = gson.fromJson(respBody, WxRespCode.class);
                if (WxRespCode.class.getName().equals(resultClass.getName()) && exJson.getErrcode() == 0) {
                    return (T) exJson;
                } else {
                    throw new WxException(exJson);
                }
            }
            T result = gson.fromJson(respBody, resultClass);
            if (result instanceof WxBaseEntity) {
                ((WxBaseEntity) result).setCreatedDate(new Date());
            }
            return result;
        }
    } catch (IOException e) {
        throw new WxException(e);
    } catch (URISyntaxException e) {
        throw new WxException(e);
    }
}
Example 92
Project: WeixinMultiPlatform-master  File: WxUtil.java View source code
@SuppressWarnings("unchecked")
public static final <T> T sendRequest(String url, HttpMethod method, Map<String, String> params, HttpEntity requestEntity, Class<T> resultClass) throws WxException {
    HttpClient client = HttpClientBuilder.create().build();
    HttpRequestBase request = null;
    try {
        if (HttpMethod.GET.equals(method)) {
            request = new HttpGet();
        } else if (HttpMethod.POST.equals(method)) {
            request = new HttpPost();
            if (requestEntity != null) {
                ((HttpPost) request).setEntity(requestEntity);
            }
        }
        URIBuilder builder = new URIBuilder(url);
        if (params != null) {
            for (Map.Entry<String, String> entry : params.entrySet()) {
                builder.addParameter(entry.getKey(), entry.getValue());
            }
        }
        request.setURI(builder.build());
        HttpResponse response = client.execute(request);
        HttpEntity entity = response.getEntity();
        String respBody = EntityUtils.toString(entity);
        if (entity != null) {
            EntityUtils.consume(entity);
        }
        if (String.class.isAssignableFrom(resultClass)) {
            return (T) respBody;
        } else {
            Gson gson = new Gson();
            if (respBody.indexOf("{\"errcode\"") == 0 || respBody.indexOf("{\"errmsg\"") == 0) {
                WxRespCode exJson = gson.fromJson(respBody, WxRespCode.class);
                if (WxRespCode.class.getName().equals(resultClass.getName()) && exJson.getErrcode() == 0) {
                    return (T) exJson;
                } else {
                    throw new WxException(exJson);
                }
            }
            T result = gson.fromJson(respBody, resultClass);
            if (result instanceof WxBaseEntity) {
                ((WxBaseEntity) result).setCreatedDate(new Date());
            }
            return result;
        }
    } catch (IOException e) {
        throw new WxException(e);
    } catch (URISyntaxException e) {
        throw new WxException(e);
    }
}
Example 93
Project: Wilma-master  File: SecondaryRequestHandler.java View source code
/**
     * Send and receives the secondary message.
     *
     * @param wilmaHttpRequest is th request
     * @param method           is httpGet or httpPut
     * @return withe the response
     * @throws IOException is issue occurs
     */
WilmaHttpResponse sendReceive(WilmaHttpRequest wilmaHttpRequest, HttpRequestBase method) throws IOException {
    String messageId = wilmaHttpRequest.getWilmaMessageId();
    String serverIpAddress = wilmaHttpRequest.getRemoteAddr();
    // copy all headers
    for (String headerKey : wilmaHttpRequest.getHeaders().keySet()) {
        String headerValue = wilmaHttpRequest.getHeader(headerKey);
        method.addHeader(headerKey, headerValue);
    }
    HttpClient httpClient = new DefaultHttpClient();
    HttpResponse response = httpClient.execute(method);
    return transferResponse(response, method, messageId, serverIpAddress);
}
Example 94
Project: aesop-master  File: UserInfoServiceScanReader.java View source code
/**
	 * Interface method implementation.Scans and retrieves a number of {@link UserInfo} instances looked up from a service end-point. The scan stops once no more 
	 * data is returned by the service endpoint.
	 * Note : The end-point and parameters used here are very specific to this sample. Also the code is mostly for testing and production 
	 * ready (no Http connection pools etc.) 
	 * @see org.springframework.batch.item.ItemReader#read()
	 */
public UserInfo read() throws Exception, UnexpectedInputException, ParseException {
    // return data from local queue if available already
    synchronized (// include the check for empty and remove in one synchronized block to avoid race conditions
    this) {
        if (!this.localQueue.isEmpty()) {
            LOGGER.debug("Returning data from local cache. Cache size : " + this.localQueue.size());
            return this.localQueue.poll();
        }
    }
    parallelFetch.acquire();
    int startIndex = 0;
    synchronized (this) {
        startIndex = resultCount += BATCH_SIZE;
    }
    if (this.resultCount < MAX_RESULTS) {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpGet executionGet = new HttpGet(BATCH_SERVICE_URL);
        URIBuilder uriBuilder = new URIBuilder(executionGet.getURI());
        uriBuilder.addParameter("start", String.valueOf(startIndex));
        uriBuilder.addParameter("count", String.valueOf(BATCH_SIZE));
        ((HttpRequestBase) executionGet).setURI(uriBuilder.build());
        HttpResponse httpResponse = httpclient.execute(executionGet);
        String response = new String(EntityUtils.toByteArray(httpResponse.getEntity()));
        ScanResult scanResult = objectMapper.readValue(response, ScanResult.class);
        if (scanResult.getCount() <= 0) {
            parallelFetch.release();
            return null;
        }
        LOGGER.info("Fetched User Info objects in range - Start : {}. Count : {}", startIndex, scanResult.getCount());
        for (UserInfo userInfo : scanResult.getResponse()) {
            this.localQueue.add(userInfo);
        }
    }
    parallelFetch.release();
    return this.localQueue.poll();
}
Example 95
Project: android-1-master  File: HttpPerformer.java View source code
public Response perform() {
    String url = request.url;
    DefaultHttpClient client = new DefaultHttpClient();
    HttpParams httpParams = client.getParams();
    if (request.options != null && request.options.get(OptionsKey.connectionTimeout) != null) {
        HttpConnectionParams.setConnectionTimeout(httpParams, (Integer) request.options.get(OptionsKey.connectionTimeout));
    } else {
        // 30 seconds for connection timeout
        HttpConnectionParams.setConnectionTimeout(httpParams, 30000);
    }
    if (request.options != null && request.options.get(OptionsKey.soTimeout) != null) {
        HttpConnectionParams.setSoTimeout(httpParams, (Integer) request.options.get(OptionsKey.soTimeout));
    } else {
        // 15 seconds for waiting for data
        HttpConnectionParams.setSoTimeout(httpParams, 15000);
    }
    // TODO make it more efficient by not buffering byte[]
    ByteArrayOutputStream os = new ByteArrayOutputStream(256);
    int httpResponseCode = 0;
    try {
        HttpRequestBase base = null;
        if (request.method == Method.GET || request.method == Method.GET_RAW) {
            url += request.params.toUrlEncodedStringWithOptionalQuestionMark();
            base = new HttpGet(url);
        } else if (request.method == Method.GET_DIGEST) {
            //$NON-NLS-1$//$NON-NLS-2$
            client.getCredentialsProvider().setCredentials(new AuthScope(null, -1), new UsernamePasswordCredentials(request.params.getAndRemove("email"), request.params.getAndRemove("passwd")));
            url += request.params.toUrlEncodedStringWithOptionalQuestionMark();
            base = new HttpGet(url);
        } else if (request.method == Method.POST) {
            HttpPost method = new HttpPost(url);
            // use params as usual
            ArrayList<NameValuePair> list = new ArrayList<NameValuePair>();
            request.params.addAllTo(list);
            //$NON-NLS-1$
            method.setEntity(//$NON-NLS-1$
            new UrlEncodedFormEntity(list, "utf-8"));
            base = method;
        } else if (request.method == Method.DELETE) {
            url += request.params.toUrlEncodedStringWithOptionalQuestionMark();
            base = new HttpDelete(url);
        } else {
            //$NON-NLS-1$ //$NON-NLS-2$
            throw new RuntimeException("http method " + request.method + " not supported yet");
        }
        request.headers.addTo(base);
        //$NON-NLS-1$//$NON-NLS-2$
        base.addHeader("Cache-Control", "no-cache");
        //$NON-NLS-1$ //$NON-NLS-2$
        base.addHeader("Accept-Encoding", "gzip");
        HttpResponse response = client.execute(base);
        httpResponseCode = response.getStatusLine().getStatusCode();
        if (task != null && task.isCancelled()) {
            base.abort();
        } else {
            Header encodingHeader = //$NON-NLS-1$
            response.getFirstHeader(//$NON-NLS-1$
            "Content-Encoding");
            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();
            try {
                if (encodingHeader != null && //$NON-NLS-1$
                encodingHeader.getValue().equalsIgnoreCase(//$NON-NLS-1$
                "gzip")) {
                    content = new GZIPInputStream(content);
                }
                byte[] buf = new byte[4096 * 4];
                while (true) {
                    int read = content.read(buf);
                    if (read <= 0)
                        break;
                    os.write(buf, 0, read);
                    if (task != null && task.isCancelled()) {
                        base.abort();
                        break;
                    }
                }
            } finally {
                if (content != null)
                    content.close();
            }
        }
    } catch (IOException e) {
        Log.d(TAG, "IoError: " + e.getClass().getSimpleName() + ": " + e.getMessage());
        return new Response(this.request, Validity.IoError, e.getClass().getName() + ": " + e.getMessage());
    }
    if (task != null && task.isCancelled()) {
        //$NON-NLS-1$
        return new Response(this.request, Validity.Cancelled, "cancelled");
    }
    return new Response(this.request, os.toByteArray(), httpResponseCode);
}
Example 96
Project: android-channel-master  File: Http.java View source code
/**
     * Fetch content from the wire, first checking if there is a cached version available.
     */
public byte[] fetch(HttpRequestBase request) throws IOException {
    // add that we accept GZIP compressed content
    request.setHeader("Accept-Encoding", "gzip");
    // dump the request to the console
    if (RapidPro.SHOW_WIRE) {
        RapidPro.LOG.d("    " + request.getMethod() + " " + request.getURI());
        for (Header header : request.getAllHeaders()) {
            RapidPro.LOG.d("    > " + header.getName() + ": " + header.getValue());
        }
    }
    long start = System.currentTimeMillis();
    try {
        HttpResponse response = m_client.execute(request);
        InputStream inputStream = new BufferedInputStream(AndroidHttpClient.getUngzippedContent(response.getEntity()));
        byte[] content = readStreamFully(inputStream);
        if (RapidPro.SHOW_WIRE) {
            String body = new String(content);
            RapidPro.LOG.d("\n    " + response.getStatusLine().toString());
            RapidPro.LOG.d("    Received response with " + content.length + " bytes");
            for (Header header : response.getAllHeaders()) {
                RapidPro.LOG.d("    < " + header.getName() + ": " + header.getValue());
            }
            RapidPro.LOG.d("    " + body);
            RapidPro.LOG.d("\n");
        }
        return content;
    } catch (IOException e) {
        request.abort();
        throw e;
    } finally {
        RapidPro.LOG.d("Fetch took: " + (System.currentTimeMillis() - start));
    }
}
Example 97
Project: Android_App_OpenSource-master  File: HttpClient4.java View source code
public HttpResponseMessage execute(HttpMessage request) throws IOException {
    final String method = request.method;
    final String url = request.url.toExternalForm();
    final InputStream body = request.getBody();
    final boolean isDelete = DELETE.equalsIgnoreCase(method);
    final boolean isPost = POST.equalsIgnoreCase(method);
    final boolean isPut = PUT.equalsIgnoreCase(method);
    byte[] excerpt = null;
    HttpRequestBase httpRequest;
    if (isPost || isPut) {
        HttpEntityEnclosingRequestBase entityEnclosingMethod = isPost ? new HttpPost(url) : new HttpPut(url);
        if (body != null) {
            ExcerptInputStream e = new ExcerptInputStream(body);
            excerpt = e.getExcerpt();
            String length = request.removeHeaders(HttpMessage.CONTENT_LENGTH);
            entityEnclosingMethod.setEntity(new InputStreamEntity(e, (length == null) ? -1 : Long.parseLong(length)));
        }
        httpRequest = entityEnclosingMethod;
    } else if (isDelete) {
        httpRequest = new HttpDelete(url);
    } else {
        httpRequest = new HttpGet(url);
    }
    for (Map.Entry<String, String> header : request.headers) {
        httpRequest.addHeader(header.getKey(), header.getValue());
    }
    HttpClient client = clientPool.getHttpClient(new URL(httpRequest.getURI().toString()));
    client.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false);
    HttpResponse httpResponse = client.execute(httpRequest);
    return new HttpMethodResponse(httpRequest, httpResponse, excerpt, request.getContentCharset());
}
Example 98
Project: api-sdk-java-master  File: HttpProxyUtilsTest.java View source code
@Before
public void setUp() {
    httpProxyUtils = spy(new HttpProxyUtils());
    httpRequest = mock(HttpRequestBase.class);
    httpClientBuilder = PowerMockito.mock(HttpClientBuilder.class);
    when(httpProxyUtils.getHttpClientBuilder()).thenReturn(httpClientBuilder);
    PowerMockito.when(httpClientBuilder.build()).then(RETURNS_MOCKS);
}
Example 99
Project: bricklink-master  File: BrickLinkClient.java View source code
public <T extends Response<?>> T execute(Request<T> request) throws Exception {
    String url = BASE_URL + request.getPath();
    HttpRequestBase httpRequest;
    switch(request.getMethod()) {
        case GET:
            httpRequest = new HttpGet(addQueryParams2URL(url, convertParameter(request)));
            break;
        case PUT:
            HttpPut put = new HttpPut(url);
            httpRequest = put;
            StringEntity entity = new StringEntity(request.getBody(), Charset.forName("UTF-8"));
            entity.setContentType("application/json");
            put.setEntity(entity);
            break;
        default:
            throw new Exception("Not implemented HTTP method: " + request.getMethod());
    }
    consumer.sign(httpRequest);
    CloseableHttpResponse httpResponse = client.execute(httpRequest);
    final T response;
    try {
        Parser<? extends T, ?> parser = request.getParser();
        String body = Parser.checkResponse(httpResponse);
        response = parser.parse(body);
    } finally {
        httpResponse.close();
    }
    return response;
}
Example 100
Project: btcd-cli4j-master  File: SimpleHttpClientImpl.java View source code
private HttpRequestBase getNewRequest(String reqMethod, String reqPayload) throws URISyntaxException, UnsupportedEncodingException {
    HttpRequestBase request;
    if (reqMethod.equals(HttpConstants.REQ_METHOD_POST)) {
        HttpPost postRequest = new HttpPost();
        postRequest.setEntity(new StringEntity(reqPayload, ContentType.create(DataFormats.JSON.getMediaType(), Constants.UTF_8)));
        request = postRequest;
    } else {
        throw new IllegalArgumentException(Errors.ARGS_HTTP_METHOD_UNSUPPORTED.getDescription());
    }
    request.setURI(new URI(String.format("%s://%s:%s/", nodeConfig.getProperty(NodeProperties.RPC_PROTOCOL.getKey()), nodeConfig.getProperty(NodeProperties.RPC_HOST.getKey()), nodeConfig.getProperty(NodeProperties.RPC_PORT.getKey()))));
    String authScheme = nodeConfig.getProperty(NodeProperties.HTTP_AUTH_SCHEME.getKey());
    request.addHeader(resolveAuthHeader(authScheme));
    LOG.debug("<< getNewRequest(..): returning a new HTTP '{}' request with target endpoint " + "'{}' and headers '{}'", reqMethod, request.getURI(), request.getAllHeaders());
    return request;
}
Example 101
Project: camel-master  File: HttpPollingConsumer.java View source code
protected Exchange doReceive(int timeout) {
    Exchange exchange = endpoint.createExchange();
    HttpRequestBase method = createMethod(exchange);
    HttpClientContext httpClientContext = new HttpClientContext();
    // set optional timeout in millis
    if (timeout > 0) {
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).build();
        httpClientContext.setRequestConfig(requestConfig);
    }
    HttpEntity responeEntity = null;
    try {
        // execute request
        HttpResponse response = httpClient.execute(method, httpClientContext);
        int responseCode = response.getStatusLine().getStatusCode();
        responeEntity = response.getEntity();
        Object body = HttpHelper.readResponseBodyFromInputStream(responeEntity.getContent(), exchange);
        // lets store the result in the output message.
        Message message = exchange.getOut();
        message.setBody(body);
        // lets set the headers
        Header[] headers = response.getAllHeaders();
        HeaderFilterStrategy strategy = endpoint.getHeaderFilterStrategy();
        for (Header header : headers) {
            String name = header.getName();
            // mapping the content-type
            if (name.toLowerCase().equals("content-type")) {
                name = Exchange.CONTENT_TYPE;
            }
            String value = header.getValue();
            if (strategy != null && !strategy.applyFilterToExternalHeaders(name, value, exchange)) {
                message.setHeader(name, value);
            }
        }
        message.setHeader(Exchange.HTTP_RESPONSE_CODE, responseCode);
        if (response.getStatusLine() != null) {
            message.setHeader(Exchange.HTTP_RESPONSE_TEXT, response.getStatusLine().getReasonPhrase());
        }
        return exchange;
    } catch (IOException e) {
        throw new RuntimeCamelException(e);
    } finally {
        if (responeEntity != null) {
            try {
                EntityUtils.consume(responeEntity);
            } catch (IOException e) {
            }
        }
    }
}