Search in sources :

Example 51 with HttpEntity

use of org.apache.http.HttpEntity in project openkit-android by OpenKit.

the class AsyncHttpResponseHandler method sendResponseMessage.

// Interface to AsyncHttpRequest
void sendResponseMessage(HttpResponse response) {
    StatusLine status = response.getStatusLine();
    String responseBody = null;
    try {
        HttpEntity entity = null;
        HttpEntity temp = response.getEntity();
        if (temp != null) {
            entity = new BufferedHttpEntity(temp);
            responseBody = EntityUtils.toString(entity, "UTF-8");
        }
    } catch (IOException e) {
        sendFailureMessage(e, (String) null);
    }
    if (status.getStatusCode() >= 300) {
        sendFailureMessage(new HttpResponseException(status.getStatusCode(), status.getReasonPhrase()), responseBody);
    } else {
        sendSuccessMessage(status.getStatusCode(), responseBody);
    }
}
Also used : StatusLine(org.apache.http.StatusLine) HttpEntity(org.apache.http.HttpEntity) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) BufferedHttpEntity(org.apache.http.entity.BufferedHttpEntity) HttpResponseException(org.apache.http.client.HttpResponseException) IOException(java.io.IOException)

Example 52 with HttpEntity

use of org.apache.http.HttpEntity in project openkit-android by OpenKit.

the class RequestParams method getEntity.

/**
     * Returns an HttpEntity containing all request parameters
     */
public HttpEntity getEntity() {
    HttpEntity entity = null;
    if (!fileParams.isEmpty()) {
        SimpleMultipartEntity multipartEntity = new SimpleMultipartEntity();
        // Add string params
        for (ConcurrentHashMap.Entry<String, String> entry : urlParams.entrySet()) {
            multipartEntity.addPart(entry.getKey(), entry.getValue());
        }
        // Add file params
        int currentIndex = 0;
        int lastIndex = fileParams.entrySet().size() - 1;
        for (ConcurrentHashMap.Entry<String, FileWrapper> entry : fileParams.entrySet()) {
            FileWrapper file = entry.getValue();
            if (file.inputStream != null) {
                boolean isLast = currentIndex == lastIndex;
                if (file.contentType != null) {
                    multipartEntity.addPart(entry.getKey(), file.getFileName(), file.inputStream, file.contentType, isLast);
                } else {
                    multipartEntity.addPart(entry.getKey(), file.getFileName(), file.inputStream, isLast);
                }
            }
            currentIndex++;
        }
        // Add dupe params
        for (ConcurrentHashMap.Entry<String, ArrayList<String>> entry : urlParamsWithArray.entrySet()) {
            ArrayList<String> values = entry.getValue();
            for (String value : values) {
                multipartEntity.addPart(entry.getKey(), value);
            }
        }
        entity = multipartEntity;
    } else {
        try {
            entity = new UrlEncodedFormEntity(getParamsList(), ENCODING);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
    return entity;
}
Also used : HttpEntity(org.apache.http.HttpEntity) ArrayList(java.util.ArrayList) UnsupportedEncodingException(java.io.UnsupportedEncodingException) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap)

Example 53 with HttpEntity

use of org.apache.http.HttpEntity in project screenbird by adamhub.

the class FileUtil method postData.

public static String[] postData(String data, final JProgressBar pbUpload, String anonymous_token, String csrf_token, String user_id, ProgressBarUploadProgressListener listener, String upload_url) throws IOException {
    HttpClient httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    HttpPost httppost = new HttpPost(upload_url);
    //File file = new File(fileLocation);
    //MultipartEntity mpEntity = new MultipartEntity();
    ProgressMultiPartEntity mpEntity = new ProgressMultiPartEntity(listener);
    //ContentBody cbFile = new FileBody(file, "video/quicktime");
    //mpEntity.addPart("videoupload", cbFile);
    //ContentBody cbToken = new StringBody(title);
    //mpEntity.addPart("csrfmiddlewaretoken", cbToken);
    ContentBody cbUser_id = new StringBody(user_id);
    mpEntity.addPart("user_id", cbUser_id);
    ContentBody cbAnonym_id = new StringBody(MediaUtil.getMacAddress());
    mpEntity.addPart("anonym_id", cbAnonym_id);
    //ContentBody cbTitle = new StringBody(title);
    //mpEntity.addPart("title", cbTitle);
    //        ContentBody cbSlug = new StringBody(slug);
    //        mpEntity.addPart("slug", cbSlug);
    //        ContentBody cbPublic = new StringBody(is_public ? "1" : "0");
    //        mpEntity.addPart("is_public", cbPublic);
    //        ContentBody cbDescription = new StringBody(description);
    //        mpEntity.addPart("description", cbDescription);
    //        ContentBody cbChecksum = new StringBody(checksum);
    //        mpEntity.addPart("checksum", cbChecksum);
    //        ContentBody cbType = new StringBody(video_type);
    //        mpEntity.addPart("video_type", cbType);
    httppost.setEntity(mpEntity);
    System.out.println("===================================================");
    System.out.println("executing request " + httppost.getRequestLine());
    System.out.println("===================================================");
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity resEntity = response.getEntity();
    String[] result = new String[2];
    String status = response.getStatusLine().toString();
    result[0] = (status.indexOf("200") >= 0) ? "200" : status;
    System.out.println("===================================================");
    System.out.println("status from request " + result[0]);
    System.out.println("===================================================");
    if (resEntity != null) {
        result[1] = EntityUtils.toString(resEntity);
        EntityUtils.consume(resEntity);
    }
    httpclient.getConnectionManager().shutdown();
    return result;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) ContentBody(org.apache.http.entity.mime.content.ContentBody) HttpEntity(org.apache.http.HttpEntity) StringBody(org.apache.http.entity.mime.content.StringBody) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) ProgressMultiPartEntity(com.bixly.pastevid.util.view.ProgressMultiPartEntity) HttpResponse(org.apache.http.HttpResponse) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient)

Example 54 with HttpEntity

use of org.apache.http.HttpEntity in project SmartAndroidSource by jaychou2012.

the class AbstractAjaxCallback method httpDo.

private void httpDo(HttpUriRequest hr, String url, Map<String, String> headers, AjaxStatus status) throws ClientProtocolException, IOException {
    if (AGENT != null) {
        hr.addHeader("User-Agent", AGENT);
    }
    if (headers != null) {
        for (String name : headers.keySet()) {
            hr.addHeader(name, headers.get(name));
        }
    }
    if (GZIP && (headers == null || !headers.containsKey("Accept-Encoding"))) {
        hr.addHeader("Accept-Encoding", "gzip");
    }
    String cookie = makeCookie();
    if (cookie != null) {
        hr.addHeader("Cookie", cookie);
    }
    if (ah != null) {
        ah.applyToken(this, hr);
    }
    DefaultHttpClient client = getClient();
    HttpParams hp = hr.getParams();
    if (proxy != null)
        hp.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    if (timeout > 0) {
        AQUtility.debug("timeout param", CoreConnectionPNames.CONNECTION_TIMEOUT);
        hp.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, timeout);
        hp.setParameter(CoreConnectionPNames.SO_TIMEOUT, timeout);
    }
    HttpContext context = new BasicHttpContext();
    CookieStore cookieStore = new BasicCookieStore();
    context.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
    request = hr;
    if (abort) {
        throw new IOException("Aborted");
    }
    HttpResponse response = client.execute(hr, context);
    byte[] data = null;
    String redirect = url;
    int code = response.getStatusLine().getStatusCode();
    String message = response.getStatusLine().getReasonPhrase();
    String error = null;
    HttpEntity entity = response.getEntity();
    Header[] hs = response.getAllHeaders();
    HashMap<String, String> responseHeaders = new HashMap<String, String>(hs.length);
    for (Header h : hs) {
        responseHeaders.put(h.getName(), h.getValue());
    }
    setResponseHeaders(responseHeaders);
    File file = null;
    if (code < 200 || code >= 300) {
        try {
            if (entity != null) {
                InputStream is = entity.getContent();
                byte[] s = toData(getEncoding(entity), is);
                error = new String(s, "UTF-8");
                AQUtility.debug("error", error);
            }
        } catch (Exception e) {
            AQUtility.debug(e);
        }
    } else {
        HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
        HttpUriRequest currentReq = (HttpUriRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST);
        redirect = currentHost.toURI() + currentReq.getURI();
        int size = Math.max(32, Math.min(1024 * 64, (int) entity.getContentLength()));
        OutputStream os = null;
        InputStream is = null;
        try {
            file = getPreFile();
            if (file == null) {
                os = new PredefinedBAOS(size);
            } else {
                file.createNewFile();
                os = new BufferedOutputStream(new FileOutputStream(file));
            }
            //AQUtility.time("copy");
            copy(entity.getContent(), os, getEncoding(entity), (int) entity.getContentLength());
            //AQUtility.timeEnd("copy", 0);
            os.flush();
            if (file == null) {
                data = ((PredefinedBAOS) os).toByteArray();
            } else {
                if (!file.exists() || file.length() == 0) {
                    file = null;
                }
            }
        } finally {
            AQUtility.close(is);
            AQUtility.close(os);
        }
    }
    AQUtility.debug("response", code);
    if (data != null) {
        AQUtility.debug(data.length, url);
    }
    status.code(code).message(message).error(error).redirect(redirect).time(new Date()).data(data).file(file).client(client).context(context).headers(response.getAllHeaders());
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) HttpEntity(org.apache.http.HttpEntity) HashMap(java.util.HashMap) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) DataOutputStream(java.io.DataOutputStream) BufferedOutputStream(java.io.BufferedOutputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpHost(org.apache.http.HttpHost) BufferedOutputStream(java.io.BufferedOutputStream) GZIPInputStream(java.util.zip.GZIPInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) HttpContext(org.apache.http.protocol.HttpContext) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) ClientProtocolException(org.apache.http.client.ClientProtocolException) IOException(java.io.IOException) Date(java.util.Date) CookieStore(org.apache.http.client.CookieStore) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) BasicHttpParams(org.apache.http.params.BasicHttpParams) HttpParams(org.apache.http.params.HttpParams) BasicCookieStore(org.apache.http.impl.client.BasicCookieStore) Header(org.apache.http.Header) FileOutputStream(java.io.FileOutputStream) File(java.io.File)

Example 55 with HttpEntity

use of org.apache.http.HttpEntity in project musicbrainz-android by jdamcd.

the class MusicBrainzWebClient method lookupUserCollections.

@Override
public LinkedList<UserCollectionInfo> lookupUserCollections() throws IOException {
    HttpEntity entity = get(QueryBuilder.collectionList());
    LinkedList<UserCollectionInfo> collections = responseParser.parseCollectionListLookup(entity.getContent());
    entity.consumeContent();
    Collections.sort(collections);
    return collections;
}
Also used : HttpEntity(org.apache.http.HttpEntity) UserCollectionInfo(org.musicbrainz.android.api.data.UserCollectionInfo)

Aggregations

HttpEntity (org.apache.http.HttpEntity)518 HttpResponse (org.apache.http.HttpResponse)185 HttpGet (org.apache.http.client.methods.HttpGet)152 IOException (java.io.IOException)144 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)105 Test (org.junit.Test)93 HttpPost (org.apache.http.client.methods.HttpPost)84 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)83 InputStream (java.io.InputStream)71 ArrayList (java.util.ArrayList)69 Header (org.apache.http.Header)64 StatusLine (org.apache.http.StatusLine)61 URI (java.net.URI)58 NameValuePair (org.apache.http.NameValuePair)58 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)58 BasicNameValuePair (org.apache.http.message.BasicNameValuePair)58 HttpClient (org.apache.http.client.HttpClient)55 StringEntity (org.apache.http.entity.StringEntity)51 InputStreamReader (java.io.InputStreamReader)44 BufferedReader (java.io.BufferedReader)41