Search in sources :

Example 6 with BasicHttpEntityEnclosingRequest

use of org.apache.http.message.BasicHttpEntityEnclosingRequest in project android_frameworks_base by ParanoidAndroid.

the class Request method setBodyProvider.

/**
     * Supply an InputStream that provides the body of a request.  It's
     * not great that the caller must also provide the length of the data
     * returned by that InputStream, but the client needs to know up
     * front, and I'm not sure how to get this out of the InputStream
     * itself without a costly readthrough.  I'm not sure skip() would
     * do what we want.  If you know a better way, please let me know.
     */
private void setBodyProvider(InputStream bodyProvider, int bodyLength) {
    if (!bodyProvider.markSupported()) {
        throw new IllegalArgumentException("bodyProvider must support mark()");
    }
    // Mark beginning of stream
    bodyProvider.mark(Integer.MAX_VALUE);
    ((BasicHttpEntityEnclosingRequest) mHttpRequest).setEntity(new InputStreamEntity(bodyProvider, bodyLength));
}
Also used : BasicHttpEntityEnclosingRequest(org.apache.http.message.BasicHttpEntityEnclosingRequest) InputStreamEntity(org.apache.http.entity.InputStreamEntity)

Example 7 with BasicHttpEntityEnclosingRequest

use of org.apache.http.message.BasicHttpEntityEnclosingRequest in project platform_external_apache-http by android.

the class Request method setBodyProvider.

/**
     * Supply an InputStream that provides the body of a request.  It's
     * not great that the caller must also provide the length of the data
     * returned by that InputStream, but the client needs to know up
     * front, and I'm not sure how to get this out of the InputStream
     * itself without a costly readthrough.  I'm not sure skip() would
     * do what we want.  If you know a better way, please let me know.
     */
private void setBodyProvider(InputStream bodyProvider, int bodyLength) {
    if (!bodyProvider.markSupported()) {
        throw new IllegalArgumentException("bodyProvider must support mark()");
    }
    // Mark beginning of stream
    bodyProvider.mark(Integer.MAX_VALUE);
    ((BasicHttpEntityEnclosingRequest) mHttpRequest).setEntity(new InputStreamEntity(bodyProvider, bodyLength));
}
Also used : BasicHttpEntityEnclosingRequest(org.apache.http.message.BasicHttpEntityEnclosingRequest) InputStreamEntity(org.apache.http.entity.InputStreamEntity)

Example 8 with BasicHttpEntityEnclosingRequest

use of org.apache.http.message.BasicHttpEntityEnclosingRequest in project cdap-ingest by caskdata.

the class StreamConfigHttpRequestHandler method handle.

@Override
public void handle(HttpRequest httpRequest, HttpResponse response, HttpContext httpContext) throws HttpException, IOException {
    RequestLine requestLine = httpRequest.getRequestLine();
    String method = requestLine.getMethod();
    int statusCode;
    if (!HttpMethod.PUT.equals(method)) {
        statusCode = HttpStatus.SC_NOT_IMPLEMENTED;
    } else {
        String uri = requestLine.getUri();
        String streamName = TestUtils.getStreamNameFromUri(uri);
        if (TestUtils.SUCCESS_STREAM_NAME.equals(streamName)) {
            statusCode = HttpStatus.SC_BAD_REQUEST;
            BasicHttpEntityEnclosingRequest request = (BasicHttpEntityEnclosingRequest) httpRequest;
            HttpEntity requestEntity = request.getEntity();
            if (requestEntity != null) {
                JsonObject jsonContent = RestClient.toJsonObject(requestEntity);
                if (jsonContent != null) {
                    long ttl = jsonContent.get(TTL_ATTRIBUTE_NAME).getAsLong();
                    if (ttl == RestTest.STREAM_TTL) {
                        statusCode = HttpStatus.SC_OK;
                    }
                }
            }
        } else if (TestUtils.AUTH_STREAM_NAME.equals(streamName)) {
            statusCode = TestUtils.authorize(httpRequest);
        } else {
            statusCode = TestUtils.getStatusCodeByStreamName(streamName);
        }
    }
    response.setStatusCode(statusCode);
}
Also used : RequestLine(org.apache.http.RequestLine) HttpEntity(org.apache.http.HttpEntity) JsonObject(com.google.gson.JsonObject) BasicHttpEntityEnclosingRequest(org.apache.http.message.BasicHttpEntityEnclosingRequest)

Example 9 with BasicHttpEntityEnclosingRequest

use of org.apache.http.message.BasicHttpEntityEnclosingRequest in project cdap-ingest by caskdata.

the class StreamHttpRequestHandler method handle.

@Override
public void handle(HttpRequest httpRequest, HttpResponse response, HttpContext httpContext) throws HttpException, IOException {
    RequestLine requestLine = httpRequest.getRequestLine();
    String method = requestLine.getMethod();
    int statusCode;
    String uri = requestLine.getUri();
    String streamName = TestUtils.getStreamNameFromUri(uri + "/");
    if (HttpMethod.PUT.equals(method)) {
        if (TestUtils.AUTH_STREAM_NAME.equals(streamName)) {
            statusCode = TestUtils.authorize(httpRequest);
        } else {
            statusCode = TestUtils.getStatusCodeByStreamName(streamName);
        }
    } else if (HttpMethod.POST.equals(method)) {
        String fullStreamName = streamName;
        streamName = streamName.replace(TestUtils.WRITER_TEST_STREAM_NAME_POSTFIX, StringUtils.EMPTY);
        if (TestUtils.AUTH_STREAM_NAME.equals(streamName)) {
            statusCode = TestUtils.authorize(httpRequest);
        } else if (TestUtils.WITH_CUSTOM_HEADER_STREAM_NAME.endsWith(streamName)) {
            Header testHeader = httpRequest.getFirstHeader(fullStreamName + "." + RestTest.TEST_HEADER_NAME);
            if (testHeader != null && RestTest.TEST_HEADER_VALUE.equals(testHeader.getValue())) {
                statusCode = HttpStatus.SC_OK;
            } else {
                statusCode = HttpStatus.SC_BAD_REQUEST;
            }
        } else {
            statusCode = TestUtils.getStatusCodeByStreamName(streamName);
        }
        if (HttpStatus.SC_OK == statusCode && !TestUtils.FILE_STREAM_NAME.equals(streamName)) {
            //check request content
            BasicHttpEntityEnclosingRequest request = (BasicHttpEntityEnclosingRequest) httpRequest;
            HttpEntity requestEntity = request.getEntity();
            if (requestEntity != null) {
                String content = RestClient.toString(requestEntity);
                if (!RestTest.EXPECTED_WRITER_CONTENT.equals(content) && !TestUtils.ALLOW_ANY_EVENT_STREAM.equals(streamName)) {
                    statusCode = HttpStatus.SC_INTERNAL_SERVER_ERROR;
                }
            } else {
                statusCode = HttpStatus.SC_BAD_REQUEST;
            }
        }
    } else {
        statusCode = HttpStatus.SC_NOT_IMPLEMENTED;
    }
    response.setStatusCode(statusCode);
}
Also used : RequestLine(org.apache.http.RequestLine) Header(org.apache.http.Header) HttpEntity(org.apache.http.HttpEntity) BasicHttpEntityEnclosingRequest(org.apache.http.message.BasicHttpEntityEnclosingRequest)

Example 10 with BasicHttpEntityEnclosingRequest

use of org.apache.http.message.BasicHttpEntityEnclosingRequest in project Talon-for-Twitter by klinker24.

the class TwitterMultipleImageHelper method uploadPics.

public boolean uploadPics(File[] pics, String text, Twitter twitter) {
    JSONObject jsonresponse = new JSONObject();
    final String ids_string = getMediaIds(pics, twitter);
    if (ids_string == null) {
        return false;
    }
    try {
        AccessToken token = twitter.getOAuthAccessToken();
        String oauth_token = token.getToken();
        String oauth_token_secret = token.getTokenSecret();
        // generate authorization header
        String get_or_post = "POST";
        String oauth_signature_method = "HMAC-SHA1";
        String uuid_string = UUID.randomUUID().toString();
        uuid_string = uuid_string.replaceAll("-", "");
        // any relatively random alphanumeric string will work here
        String oauth_nonce = uuid_string;
        // get the timestamp
        Calendar tempcal = Calendar.getInstance();
        // get current time in milliseconds
        long ts = tempcal.getTimeInMillis();
        // then divide by 1000 to get seconds
        String oauth_timestamp = (new Long(ts / 1000)).toString();
        // the parameter string must be in alphabetical order, "text" parameter added at end
        String parameter_string = "oauth_consumer_key=" + AppSettings.TWITTER_CONSUMER_KEY + "&oauth_nonce=" + oauth_nonce + "&oauth_signature_method=" + oauth_signature_method + "&oauth_timestamp=" + oauth_timestamp + "&oauth_token=" + encode(oauth_token) + "&oauth_version=1.0";
        System.out.println("Twitter.updateStatusWithMedia(): parameter_string=" + parameter_string);
        String twitter_endpoint = "https://api.twitter.com/1.1/statuses/update.json";
        String twitter_endpoint_host = "api.twitter.com";
        String twitter_endpoint_path = "/1.1/statuses/update.json";
        String signature_base_string = get_or_post + "&" + encode(twitter_endpoint) + "&" + encode(parameter_string);
        String oauth_signature = computeSignature(signature_base_string, AppSettings.TWITTER_CONSUMER_SECRET + "&" + encode(oauth_token_secret));
        String authorization_header_string = "OAuth oauth_consumer_key=\"" + AppSettings.TWITTER_CONSUMER_KEY + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"" + oauth_timestamp + "\",oauth_nonce=\"" + oauth_nonce + "\",oauth_version=\"1.0\",oauth_signature=\"" + encode(oauth_signature) + "\",oauth_token=\"" + encode(oauth_token) + "\"";
        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, "UTF-8");
        HttpProtocolParams.setUserAgent(params, "HttpCore/1.1");
        HttpProtocolParams.setUseExpectContinue(params, false);
        HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] { // Required protocol interceptors
        new RequestContent(), new RequestTargetHost(), // Recommended protocol interceptors
        new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() });
        HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
        HttpContext context = new BasicHttpContext(null);
        HttpHost host = new HttpHost(twitter_endpoint_host, 443);
        DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
        context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
        context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);
        try {
            try {
                SSLContext sslcontext = SSLContext.getInstance("TLS");
                sslcontext.init(null, null, null);
                SSLSocketFactory ssf = sslcontext.getSocketFactory();
                Socket socket = ssf.createSocket();
                socket.connect(new InetSocketAddress(host.getHostName(), host.getPort()), 0);
                conn.bind(socket, params);
                BasicHttpEntityEnclosingRequest request2 = new BasicHttpEntityEnclosingRequest("POST", twitter_endpoint_path);
                MultipartEntity reqEntity = new MultipartEntity();
                reqEntity.addPart("media_ids", new StringBody(ids_string));
                reqEntity.addPart("status", new StringBody(text));
                reqEntity.addPart("trim_user", new StringBody("1"));
                request2.setEntity(reqEntity);
                request2.setParams(params);
                request2.addHeader("Authorization", authorization_header_string);
                httpexecutor.preProcess(request2, httpproc, context);
                HttpResponse response2 = httpexecutor.execute(request2, conn, context);
                response2.setParams(params);
                httpexecutor.postProcess(response2, httpproc, context);
                String responseBody = EntityUtils.toString(response2.getEntity());
                System.out.println("response=" + responseBody);
                // error checking here. Otherwise, status should be updated.
                jsonresponse = new JSONObject(responseBody);
                conn.close();
            } catch (HttpException he) {
                System.out.println(he.getMessage());
                jsonresponse.put("response_status", "error");
                jsonresponse.put("message", "updateStatus HttpException message=" + he.getMessage());
            } catch (NoSuchAlgorithmException nsae) {
                System.out.println(nsae.getMessage());
                jsonresponse.put("response_status", "error");
                jsonresponse.put("message", "updateStatus NoSuchAlgorithmException message=" + nsae.getMessage());
            } catch (KeyManagementException kme) {
                System.out.println(kme.getMessage());
                jsonresponse.put("response_status", "error");
                jsonresponse.put("message", "updateStatus KeyManagementException message=" + kme.getMessage());
            } finally {
                conn.close();
            }
        } catch (JSONException jsone) {
            jsone.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    } catch (Exception e) {
    }
    return true;
}
Also used : InetSocketAddress(java.net.InetSocketAddress) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyManagementException(java.security.KeyManagementException) MultipartEntity(org.apache.http.entity.mime.MultipartEntity) AccessToken(twitter4j.auth.AccessToken) BasicHttpParams(org.apache.http.params.BasicHttpParams) SyncBasicHttpParams(org.apache.http.params.SyncBasicHttpParams) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) BasicHttpEntityEnclosingRequest(org.apache.http.message.BasicHttpEntityEnclosingRequest) Calendar(java.util.Calendar) JSONException(org.json.JSONException) DefaultHttpClientConnection(org.apache.http.impl.DefaultHttpClientConnection) SSLContext(javax.net.ssl.SSLContext) IOException(java.io.IOException) JSONException(org.json.JSONException) GeneralSecurityException(java.security.GeneralSecurityException) KeyManagementException(java.security.KeyManagementException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) TwitterException(twitter4j.TwitterException) IOException(java.io.IOException) BasicHttpParams(org.apache.http.params.BasicHttpParams) SyncBasicHttpParams(org.apache.http.params.SyncBasicHttpParams) HttpParams(org.apache.http.params.HttpParams) JSONObject(org.json.JSONObject) StringBody(org.apache.http.entity.mime.content.StringBody) Socket(java.net.Socket)

Aggregations

BasicHttpEntityEnclosingRequest (org.apache.http.message.BasicHttpEntityEnclosingRequest)10 IOException (java.io.IOException)5 UnsupportedEncodingException (java.io.UnsupportedEncodingException)5 InetSocketAddress (java.net.InetSocketAddress)5 Socket (java.net.Socket)5 GeneralSecurityException (java.security.GeneralSecurityException)5 SSLContext (javax.net.ssl.SSLContext)5 SSLSocketFactory (javax.net.ssl.SSLSocketFactory)5 DefaultHttpClientConnection (org.apache.http.impl.DefaultHttpClientConnection)5 BasicHttpParams (org.apache.http.params.BasicHttpParams)5 HttpParams (org.apache.http.params.HttpParams)5 Calendar (java.util.Calendar)4 AccessToken (twitter4j.auth.AccessToken)4 KeyManagementException (java.security.KeyManagementException)3 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)3 InputStreamEntity (org.apache.http.entity.InputStreamEntity)3 SyncBasicHttpParams (org.apache.http.params.SyncBasicHttpParams)3 JSONException (org.json.JSONException)3 JSONObject (org.json.JSONObject)3 TwitterException (twitter4j.TwitterException)3