Search in sources :

Example 26 with HttpPost

use of org.apache.http.client.methods.HttpPost in project UltimateAndroid by cymcsg.

the class HttpUtils method uploadFilesMPE.

/**
     * Update Files via Multipart
     *
     * @param url
     * @param paramsList
     * @param fileParams
     * @param file
     * @param files
     * @return status
     * @deprecated
     */
public static String uploadFilesMPE(String url, List<NameValuePair> paramsList, String fileParams, File file, File... files) {
    String result = "";
    try {
        DefaultHttpClient mHttpClient;
        HttpParams params = new BasicHttpParams();
        params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);
        params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 30000);
        mHttpClient = new DefaultHttpClient(params);
        HttpPost httpPost = new HttpPost(url);
        MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        if (BasicUtils.judgeNotNull(paramsList)) {
            for (NameValuePair nameValuePair : paramsList) {
                multipartEntity.addPart(nameValuePair.getName(), new StringBody(nameValuePair.getValue()));
            }
        }
        multipartEntity.addPart(fileParams, new FileBody(file));
        for (File f : files) {
            multipartEntity.addPart(fileParams, new FileBody(f));
        }
        httpPost.setEntity(multipartEntity);
        HttpResponse httpResp = mHttpClient.execute(httpPost);
        // 判断是够请求成功
        if (httpResp.getStatusLine().getStatusCode() == 200) {
            // 获取返回的数据
            result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");
            Logs.d("HttpPost success :");
            Logs.d(result);
        } else {
            Logs.d("HttpPost failed" + "    " + httpResp.getStatusLine().getStatusCode() + "   " + EntityUtils.toString(httpResp.getEntity(), "UTF-8"));
            result = "HttpPost failed";
        }
    } catch (ConnectTimeoutException e) {
        result = "ConnectTimeoutException";
        Logs.e("HttpPost overtime:  " + "");
    } catch (Exception e) {
        e.printStackTrace();
        Logs.e(e, "");
        result = "Exception";
    }
    return result;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) FileBody(org.apache.http.entity.mime.content.FileBody) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException) MultipartEntity(org.apache.http.entity.mime.MultipartEntity) StringBody(org.apache.http.entity.mime.content.StringBody) File(java.io.File) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException)

Example 27 with HttpPost

use of org.apache.http.client.methods.HttpPost in project Fling by entertailion.

the class HttpRequestHelper method sendPostStream.

public boolean sendPostStream(String url, Map<String, String> params, String contentType, OutputStream outstream) {
    boolean success = false;
    try {
        httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);
        httpPost = new HttpPost(url);
        response = null;
        Log.d(TAG, "Setting httpPost headers");
        httpPost.setHeader("Accept", "text/html,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5");
        if (contentType != null) {
            httpPost.setHeader("Content-Type", contentType);
        } else {
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
        }
        httpPost.setEntity(buildData(params));
        response = httpClient.execute(httpPost, localContext);
        if (response != null) {
            response.getEntity().writeTo(outstream);
            success = true;
        }
    } catch (Throwable e) {
        Log.e(TAG, "Failed to post to url: " + url, e);
    }
    Log.d(TAG, "Returning value:" + success);
    return success;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost)

Example 28 with HttpPost

use of org.apache.http.client.methods.HttpPost in project elasticsearch by elastic.

the class RestClientSingleHostTests method performRandomRequest.

private HttpUriRequest performRandomRequest(String method) throws Exception {
    String uriAsString = "/" + randomStatusCode(getRandom());
    URIBuilder uriBuilder = new URIBuilder(uriAsString);
    final Map<String, String> params = new HashMap<>();
    boolean hasParams = randomBoolean();
    if (hasParams) {
        int numParams = randomIntBetween(1, 3);
        for (int i = 0; i < numParams; i++) {
            String paramKey = "param-" + i;
            String paramValue = randomAsciiOfLengthBetween(3, 10);
            params.put(paramKey, paramValue);
            uriBuilder.addParameter(paramKey, paramValue);
        }
    }
    if (randomBoolean()) {
        //randomly add some ignore parameter, which doesn't get sent as part of the request
        String ignore = Integer.toString(randomFrom(RestClientTestUtil.getAllErrorStatusCodes()));
        if (randomBoolean()) {
            ignore += "," + Integer.toString(randomFrom(RestClientTestUtil.getAllErrorStatusCodes()));
        }
        params.put("ignore", ignore);
    }
    URI uri = uriBuilder.build();
    HttpUriRequest request;
    switch(method) {
        case "DELETE":
            request = new HttpDeleteWithEntity(uri);
            break;
        case "GET":
            request = new HttpGetWithEntity(uri);
            break;
        case "HEAD":
            request = new HttpHead(uri);
            break;
        case "OPTIONS":
            request = new HttpOptions(uri);
            break;
        case "PATCH":
            request = new HttpPatch(uri);
            break;
        case "POST":
            request = new HttpPost(uri);
            break;
        case "PUT":
            request = new HttpPut(uri);
            break;
        case "TRACE":
            request = new HttpTrace(uri);
            break;
        default:
            throw new UnsupportedOperationException("method not supported: " + method);
    }
    HttpEntity entity = null;
    boolean hasBody = request instanceof HttpEntityEnclosingRequest && getRandom().nextBoolean();
    if (hasBody) {
        entity = new StringEntity(randomAsciiOfLengthBetween(10, 100), ContentType.APPLICATION_JSON);
        ((HttpEntityEnclosingRequest) request).setEntity(entity);
    }
    Header[] headers = new Header[0];
    final Set<String> uniqueNames = new HashSet<>();
    if (randomBoolean()) {
        headers = RestClientTestUtil.randomHeaders(getRandom(), "Header");
        for (Header header : headers) {
            request.addHeader(header);
            uniqueNames.add(header.getName());
        }
    }
    for (Header defaultHeader : defaultHeaders) {
        // request level headers override default headers
        if (uniqueNames.contains(defaultHeader.getName()) == false) {
            request.addHeader(defaultHeader);
        }
    }
    try {
        if (hasParams == false && hasBody == false && randomBoolean()) {
            restClient.performRequest(method, uriAsString, headers);
        } else if (hasBody == false && randomBoolean()) {
            restClient.performRequest(method, uriAsString, params, headers);
        } else {
            restClient.performRequest(method, uriAsString, params, entity, headers);
        }
    } catch (ResponseException e) {
    //all good
    }
    return request;
}
Also used : HttpUriRequest(org.apache.http.client.methods.HttpUriRequest) HttpPost(org.apache.http.client.methods.HttpPost) HttpEntity(org.apache.http.HttpEntity) HashMap(java.util.HashMap) HttpOptions(org.apache.http.client.methods.HttpOptions) URI(java.net.URI) HttpHead(org.apache.http.client.methods.HttpHead) HttpPatch(org.apache.http.client.methods.HttpPatch) HttpPut(org.apache.http.client.methods.HttpPut) StringEntity(org.apache.http.entity.StringEntity) HttpEntityEnclosingRequest(org.apache.http.HttpEntityEnclosingRequest) HashSet(java.util.HashSet) URIBuilder(org.apache.http.client.utils.URIBuilder) HttpTrace(org.apache.http.client.methods.HttpTrace) Header(org.apache.http.Header)

Example 29 with HttpPost

use of org.apache.http.client.methods.HttpPost in project elasticsearch by elastic.

the class RestClient method createHttpRequest.

private static HttpRequestBase createHttpRequest(String method, URI uri, HttpEntity entity) {
    switch(method.toUpperCase(Locale.ROOT)) {
        case HttpDeleteWithEntity.METHOD_NAME:
            return addRequestBody(new HttpDeleteWithEntity(uri), entity);
        case HttpGetWithEntity.METHOD_NAME:
            return addRequestBody(new HttpGetWithEntity(uri), entity);
        case HttpHead.METHOD_NAME:
            return addRequestBody(new HttpHead(uri), entity);
        case HttpOptions.METHOD_NAME:
            return addRequestBody(new HttpOptions(uri), entity);
        case HttpPatch.METHOD_NAME:
            return addRequestBody(new HttpPatch(uri), entity);
        case HttpPost.METHOD_NAME:
            HttpPost httpPost = new HttpPost(uri);
            addRequestBody(httpPost, entity);
            return httpPost;
        case HttpPut.METHOD_NAME:
            return addRequestBody(new HttpPut(uri), entity);
        case HttpTrace.METHOD_NAME:
            return addRequestBody(new HttpTrace(uri), entity);
        default:
            throw new UnsupportedOperationException("http method not supported: " + method);
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) HttpTrace(org.apache.http.client.methods.HttpTrace) HttpOptions(org.apache.http.client.methods.HttpOptions) HttpHead(org.apache.http.client.methods.HttpHead) HttpPatch(org.apache.http.client.methods.HttpPatch) HttpPut(org.apache.http.client.methods.HttpPut)

Example 30 with HttpPost

use of org.apache.http.client.methods.HttpPost in project android_frameworks_base by ParanoidAndroid.

the class BandwidthTestUtil method postFileToServer.

/**
     * Post a given file for a given device and timestamp to the server.
     * @param server {@link String} url of test server
     * @param deviceId {@link String} device id that is uploading
     * @param timestamp {@link String} timestamp
     * @param file {@link File} to upload
     * @return true if it succeeded
     */
public static boolean postFileToServer(String server, String deviceId, String timestamp, File file) {
    try {
        Log.d(LOG_TAG, "Uploading begining");
        HttpClient httpClient = new DefaultHttpClient();
        String uri = server;
        if (!uri.endsWith("/")) {
            uri += "/";
        }
        uri += "upload";
        Log.d(LOG_TAG, "Upload url:" + uri);
        HttpPost postRequest = new HttpPost(uri);
        Part[] parts = { new StringPart("device_id", deviceId), new StringPart("timestamp", timestamp), new FilePart("file", file) };
        MultipartEntity reqEntity = new MultipartEntity(parts, postRequest.getParams());
        postRequest.setEntity(reqEntity);
        HttpResponse res = httpClient.execute(postRequest);
        res.getEntity().getContent().close();
    } catch (IOException e) {
        Log.e(LOG_TAG, "Could not upload file with error: " + e);
        return false;
    }
    return true;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) MultipartEntity(com.android.internal.http.multipart.MultipartEntity) Part(com.android.internal.http.multipart.Part) FilePart(com.android.internal.http.multipart.FilePart) StringPart(com.android.internal.http.multipart.StringPart) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) StringPart(com.android.internal.http.multipart.StringPart) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) FilePart(com.android.internal.http.multipart.FilePart)

Aggregations

HttpPost (org.apache.http.client.methods.HttpPost)531 HttpResponse (org.apache.http.HttpResponse)238 StringEntity (org.apache.http.entity.StringEntity)220 Test (org.junit.Test)153 IOException (java.io.IOException)143 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)107 UrlEncodedFormEntity (org.apache.http.client.entity.UrlEncodedFormEntity)99 BasicNameValuePair (org.apache.http.message.BasicNameValuePair)90 ArrayList (java.util.ArrayList)86 NameValuePair (org.apache.http.NameValuePair)84 HttpEntity (org.apache.http.HttpEntity)83 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)68 HttpClient (org.apache.http.client.HttpClient)64 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)63 HttpGet (org.apache.http.client.methods.HttpGet)55 TestHttpClient (io.undertow.testutils.TestHttpClient)54 ObjectNode (com.fasterxml.jackson.databind.node.ObjectNode)49 ClientProtocolException (org.apache.http.client.ClientProtocolException)49 JsonNode (com.fasterxml.jackson.databind.JsonNode)39 InputStream (java.io.InputStream)29