Search in sources :

Example 51 with ByteArrayEntity

use of org.apache.http.entity.ByteArrayEntity in project feign by OpenFeign.

the class ApacheHttpClient method toHttpUriRequest.

HttpUriRequest toHttpUriRequest(Request request, Request.Options options) throws UnsupportedEncodingException, MalformedURLException, URISyntaxException {
    RequestBuilder requestBuilder = RequestBuilder.create(request.method());
    //per request timeouts
    RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(options.connectTimeoutMillis()).setSocketTimeout(options.readTimeoutMillis()).build();
    requestBuilder.setConfig(requestConfig);
    URI uri = new URIBuilder(request.url()).build();
    requestBuilder.setUri(uri.getScheme() + "://" + uri.getAuthority() + uri.getRawPath());
    //request query params
    List<NameValuePair> queryParams = URLEncodedUtils.parse(uri, requestBuilder.getCharset().name());
    for (NameValuePair queryParam : queryParams) {
        requestBuilder.addParameter(queryParam);
    }
    //request headers
    boolean hasAcceptHeader = false;
    for (Map.Entry<String, Collection<String>> headerEntry : request.headers().entrySet()) {
        String headerName = headerEntry.getKey();
        if (headerName.equalsIgnoreCase(ACCEPT_HEADER_NAME)) {
            hasAcceptHeader = true;
        }
        if (headerName.equalsIgnoreCase(Util.CONTENT_LENGTH)) {
            // doesn't like us to set it as well.
            continue;
        }
        for (String headerValue : headerEntry.getValue()) {
            requestBuilder.addHeader(headerName, headerValue);
        }
    }
    //some servers choke on the default accept string, so we'll set it to anything
    if (!hasAcceptHeader) {
        requestBuilder.addHeader(ACCEPT_HEADER_NAME, "*/*");
    }
    //request body
    if (request.body() != null) {
        HttpEntity entity = null;
        if (request.charset() != null) {
            ContentType contentType = getContentType(request);
            String content = new String(request.body(), request.charset());
            entity = new StringEntity(content, contentType);
        } else {
            entity = new ByteArrayEntity(request.body());
        }
        requestBuilder.setEntity(entity);
    }
    return requestBuilder.build();
}
Also used : RequestConfig(org.apache.http.client.config.RequestConfig) NameValuePair(org.apache.http.NameValuePair) RequestBuilder(org.apache.http.client.methods.RequestBuilder) HttpEntity(org.apache.http.HttpEntity) ContentType(org.apache.http.entity.ContentType) URI(java.net.URI) URIBuilder(org.apache.http.client.utils.URIBuilder) StringEntity(org.apache.http.entity.StringEntity) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity) Collection(java.util.Collection) HashMap(java.util.HashMap) Map(java.util.Map)

Example 52 with ByteArrayEntity

use of org.apache.http.entity.ByteArrayEntity in project platformlayer by platformlayer.

the class MetricClientImpl method sendMetrics.

// TODO: Throw on failure??
@Override
public boolean sendMetrics(MetricTreeObject tree) {
    if (tags != null) {
        tree.mergeTree(tags);
    }
    URI url = metricBaseUrl.resolve("api/metric/").resolve(project);
    HttpPost request = new HttpPost(url);
    HttpResponse response = null;
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        metricTreeSerializer.serialize(tree, baos);
        baos.close();
        byte[] data = baos.toByteArray();
        log.debug("POSTing " + new String(data));
        // TODO: Stream body? We'd just need a custom ByteArrayEntity class
        request.setEntity(new ByteArrayEntity(data));
        response = httpClient.execute(request);
        StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() != 200) {
            log.warn("Error writing to PlatformLayer metrics server: " + statusLine);
            return false;
        } else {
            EntityUtils.consume(response.getEntity());
            response = null;
            // consumeResponse(request, response);
            log.debug("Posted metrics");
            return true;
        }
    } catch (IOException e) {
        if (log.isDebugEnabled()) {
            log.debug("Error writing to PlatformLayer metrics server", e);
        }
        log.warn("Error writing to PlatformLayer metrics server {}", e.getMessage());
        return false;
    } finally {
        if (response != null) {
            try {
                EntityUtils.consume(response.getEntity());
            } catch (IOException e) {
                log.warn("Error consuming response", e);
            }
        }
    }
}
Also used : StatusLine(org.apache.http.StatusLine) HttpPost(org.apache.http.client.methods.HttpPost) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity) HttpResponse(org.apache.http.HttpResponse) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) URI(java.net.URI)

Example 53 with ByteArrayEntity

use of org.apache.http.entity.ByteArrayEntity in project JamsMusicPlayer by psaravan.

the class GMusicClientCalls method getPlaylistEntriesWebClient.

/**************************************************************************************************
	 * Retrieves a JSONAray with all songs within the <b><i>specified</b></i> playlist. The JSONArray 
	 * contains the fields of the songs such as "id", "clientId", "trackId", etc. (for a list 
	 * of all fields, see WebClientSongsSchema.java). Uses the WebClient endpoint.
	 * 
	 * @return A JSONArray object that contains the songs and their fields within the specified playlist.
	 * @param context The context to use while retrieving songs from the playlist.
	 * @param playlistId The id of the playlist we need to fetch the songs from.
	 **************************************************************************************************/
public static final JSONArray getPlaylistEntriesWebClient(Context context, String playlistId) throws JSONException, IllegalArgumentException {
    JSONObject jsonParam = new JSONObject();
    jsonParam.putOpt("id", playlistId);
    JSONForm form = new JSONForm();
    form.addField("json", jsonParam.toString());
    form.close();
    mHttpClient.setUserAgent(mMobileClientUserAgent);
    String result = mHttpClient.post(context, "https://play.google.com/music/services/loadplaylist?u=0&xt=" + getXtCookieValue(), new ByteArrayEntity(form.toString().getBytes()), form.getContentType());
    JSONArray jsonArray = new JSONArray();
    JSONObject jsonObject = new JSONObject(result);
    if (jsonObject != null) {
        jsonArray = jsonObject.getJSONArray("playlist");
    }
    return jsonArray;
}
Also used : JSONObject(org.json.JSONObject) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity) JSONArray(org.json.JSONArray)

Example 54 with ByteArrayEntity

use of org.apache.http.entity.ByteArrayEntity in project JamsMusicPlayer by psaravan.

the class GMusicClientCalls method login.

/*******************************************************************************
	 * Attempts to log the user into the "sj" (SkyJam) service using the provided
	 * authentication token. The authentication token is unique for each session 
	 * and user account. It can be obtained via the GoogleAuthUtil.getToken() 
	 * method. See AsyncGoogleMusicAuthenticationTask.java for the current
	 * implementation of this process. This method will return true if the login
	 * process succeeded. Returns false for any other type of failure.
	 * 
	 * @param context The context that will be used for the login process.
	 * @param authToken The authentication token that will be used to login. 
	 *******************************************************************************/
public static final boolean login(Context context, String authToken) {
    if (!TextUtils.isEmpty(authToken)) {
        JSONForm form = new JSONForm().close();
        GMusicClientCalls.setAuthorizationHeader(authToken);
        String response = mHttpClient.post(context, "https://play.google.com/music/listen?hl=en&u=0", new ByteArrayEntity(form.toString().getBytes()), form.getContentType());
        //Check if the required paramters are null.
        if (response != null) {
            if (getXtCookieValue() != null) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    } else {
        return false;
    }
}
Also used : ByteArrayEntity(org.apache.http.entity.ByteArrayEntity)

Example 55 with ByteArrayEntity

use of org.apache.http.entity.ByteArrayEntity in project JamsMusicPlayer by psaravan.

the class GMusicClientCalls method modifyPlaylist.

/******************************************************************************************
	 * Executes a single/batch modification operation on a playlist's entry(ies). This method 
	 * is a general purpose method that simply hits the MobileClient endpoints using
	 * mPlaylistEntriesMutationsArray. Supported mutation operations include "create", 
	 * "delete", and "update". 
	 * 
	 * @param context The context to use while carrying out the modification operation.
	 * @param mutationsArray The JSONArray that contains the mutations command to be 
	 * carried out.
	 * @return The JSON response as a String.
	 * @throws JSONException
	 * @throws IllegalArgumentException
	 ******************************************************************************************/
public static final String modifyPlaylist(Context context) throws JSONException, IllegalArgumentException {
    JSONObject jsonParam = new JSONObject();
    jsonParam.put("mutations", mPlaylistEntriesMutationsArray);
    mHttpClient.setUserAgent(mMobileClientUserAgent);
    String result = mHttpClient.post(context, "https://www.googleapis.com/sj/v1.1/plentriesbatch?alt=json&hl=en_US", new ByteArrayEntity(jsonParam.toString().getBytes()), "application/json");
    mHttpClient.setUserAgent(mWebClientUserAgent);
    //Clear out and reset the mutationsArray now that we're done using it.
    mPlaylistEntriesMutationsArray = null;
    mPlaylistEntriesMutationsArray = new JSONArray();
    return result;
}
Also used : JSONObject(org.json.JSONObject) ByteArrayEntity(org.apache.http.entity.ByteArrayEntity) JSONArray(org.json.JSONArray)

Aggregations

ByteArrayEntity (org.apache.http.entity.ByteArrayEntity)74 HttpEntity (org.apache.http.HttpEntity)25 HttpPost (org.apache.http.client.methods.HttpPost)22 HttpResponse (org.apache.http.HttpResponse)19 ByteArrayOutputStream (java.io.ByteArrayOutputStream)15 IOException (java.io.IOException)13 JSONObject (org.json.JSONObject)10 Test (org.junit.Test)10 HttpClient (org.apache.http.client.HttpClient)8 JSONArray (org.json.JSONArray)7 InputStream (java.io.InputStream)6 AbstractHttpEntity (org.apache.http.entity.AbstractHttpEntity)5 BytesRef (org.apache.lucene.util.BytesRef)5 DocWriteRequest (org.elasticsearch.action.DocWriteRequest)5 BulkRequest (org.elasticsearch.action.bulk.BulkRequest)5 DeleteRequest (org.elasticsearch.action.delete.DeleteRequest)5 GetRequest (org.elasticsearch.action.get.GetRequest)5 IndexRequest (org.elasticsearch.action.index.IndexRequest)5 WriteRequest (org.elasticsearch.action.support.WriteRequest)5 UpdateRequest (org.elasticsearch.action.update.UpdateRequest)5