Search in sources :

Example 16 with MultipartEntity

use of org.apache.http.entity.mime.MultipartEntity in project nanohttpd by NanoHttpd.

the class GetAndPostIntegrationTest method testPostRequestWithMultipartExtremEncodedParameters.

@Test
public void testPostRequestWithMultipartExtremEncodedParameters() throws Exception {
    this.testServer.response = "testPostRequestWithMultipartEncodedParameters";
    HttpPost httppost = new HttpPost("http://localhost:8192/chin");
    MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, "sfsadfasdf", Charset.forName("UTF-8"));
    reqEntity.addPart("specialString", new StringBody("拖拉图片到浏览器,可以实现预览功能", "text/plain", Charset.forName("UTF-8")));
    reqEntity.addPart("gender", new StringBody("图片名称", Charset.forName("UTF-8")) {

        @Override
        public String getFilename() {
            return "图片名称";
        }
    });
    httppost.setEntity(reqEntity);
    HttpResponse response = this.httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();
    String responseBody = EntityUtils.toString(entity, "UTF-8");
    assertEquals("POST:testPostRequestWithMultipartEncodedParameters-params=2;gender=图片名称;specialString=拖拉图片到浏览器,可以实现预览功能", responseBody);
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) HttpEntity(org.apache.http.HttpEntity) MultipartEntity(org.apache.http.entity.mime.MultipartEntity) StringBody(org.apache.http.entity.mime.content.StringBody) HttpResponse(org.apache.http.HttpResponse) Test(org.junit.Test)

Example 17 with MultipartEntity

use of org.apache.http.entity.mime.MultipartEntity in project nanohttpd by NanoHttpd.

the class GetAndPostIntegrationTest method testPostRequestWithMultipartEncodedParameters.

@Test
public void testPostRequestWithMultipartEncodedParameters() throws Exception {
    this.testServer.response = "testPostRequestWithMultipartEncodedParameters";
    HttpPost httppost = new HttpPost("http://localhost:8192/");
    MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    reqEntity.addPart("age", new StringBody("120"));
    reqEntity.addPart("gender", new StringBody("Male"));
    httppost.setEntity(reqEntity);
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    String responseBody = this.httpclient.execute(httppost, responseHandler);
    assertEquals("POST:testPostRequestWithMultipartEncodedParameters-params=2;age=120;gender=Male", responseBody);
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) MultipartEntity(org.apache.http.entity.mime.MultipartEntity) StringBody(org.apache.http.entity.mime.content.StringBody) BasicResponseHandler(org.apache.http.impl.client.BasicResponseHandler) Test(org.junit.Test)

Example 18 with MultipartEntity

use of org.apache.http.entity.mime.MultipartEntity in project ninja by ninjaframework.

the class NinjaTestBrowser method uploadFile.

public String uploadFile(String url, String paramName, File fileToUpload) {
    String response = null;
    try {
        httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        HttpPost post = new HttpPost(url);
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        // For File parameters
        entity.addPart(paramName, new FileBody((File) fileToUpload));
        post.setEntity(entity);
        // Here we go!
        response = EntityUtils.toString(httpClient.execute(post).getEntity(), "UTF-8");
        post.releaseConnection();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return response;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) FileBody(org.apache.http.entity.mime.content.FileBody) MultipartEntity(org.apache.http.entity.mime.MultipartEntity) File(java.io.File) IOException(java.io.IOException)

Example 19 with MultipartEntity

use of org.apache.http.entity.mime.MultipartEntity in project FBReaderJ by geometer.

the class ZLNetworkManager method perform.

void perform(ZLNetworkRequest request, BearerAuthenticator authenticator, int socketTimeout, int connectionTimeout) throws ZLNetworkException {
    boolean success = false;
    DefaultHttpClient httpClient = null;
    HttpEntity entity = null;
    try {
        final HttpContext httpContext = new BasicHttpContext();
        httpContext.setAttribute(ClientContext.COOKIE_STORE, CookieStore);
        request.doBefore();
        final HttpParams params = new BasicHttpParams();
        HttpConnectionParams.setSoTimeout(params, socketTimeout);
        HttpConnectionParams.setConnectionTimeout(params, connectionTimeout);
        httpClient = new DefaultHttpClient(params) {

            protected AuthenticationHandler createTargetAuthenticationHandler() {
                final AuthenticationHandler base = super.createTargetAuthenticationHandler();
                return new AuthenticationHandler() {

                    public Map<String, Header> getChallenges(HttpResponse response, HttpContext context) throws MalformedChallengeException {
                        return base.getChallenges(response, context);
                    }

                    public boolean isAuthenticationRequested(HttpResponse response, HttpContext context) {
                        return base.isAuthenticationRequested(response, context);
                    }

                    public AuthScheme selectScheme(Map<String, Header> challenges, HttpResponse response, HttpContext context) throws AuthenticationException {
                        try {
                            return base.selectScheme(challenges, response, context);
                        } catch (AuthenticationException e) {
                            final Header bearerHeader = challenges.get("bearer");
                            if (bearerHeader != null) {
                                String realm = null;
                                for (HeaderElement elt : bearerHeader.getElements()) {
                                    final String name = elt.getName();
                                    if (name == null) {
                                        continue;
                                    }
                                    if ("realm".equals(name) || name.endsWith(" realm")) {
                                        realm = elt.getValue();
                                        break;
                                    }
                                }
                                throw new BearerAuthenticationException(realm, response.getEntity());
                            }
                            throw e;
                        }
                    }
                };
            }
        };
        final HttpRequestBase httpRequest;
        if (request instanceof ZLNetworkRequest.Get) {
            httpRequest = new HttpGet(request.URL);
        } else if (request instanceof ZLNetworkRequest.PostWithBody) {
            httpRequest = new HttpPost(request.URL);
            ((HttpPost) httpRequest).setEntity(new StringEntity(((ZLNetworkRequest.PostWithBody) request).Body, "utf-8"));
        /*
					httpConnection.setRequestProperty(
						"Content-Length",
						Integer.toString(request.Body.getBytes().length)
					);
				*/
        } else if (request instanceof ZLNetworkRequest.PostWithMap) {
            final Map<String, String> parameters = ((ZLNetworkRequest.PostWithMap) request).PostParameters;
            httpRequest = new HttpPost(request.URL);
            final List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>(parameters.size());
            for (Map.Entry<String, String> entry : parameters.entrySet()) {
                list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
            ((HttpPost) httpRequest).setEntity(new UrlEncodedFormEntity(list, "utf-8"));
        } else if (request instanceof ZLNetworkRequest.FileUpload) {
            final ZLNetworkRequest.FileUpload uploadRequest = (ZLNetworkRequest.FileUpload) request;
            final File file = ((ZLNetworkRequest.FileUpload) request).File;
            httpRequest = new HttpPost(request.URL);
            final MultipartEntity data = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null, Charset.forName("utf-8"));
            data.addPart("file", new FileBody(uploadRequest.File));
            ((HttpPost) httpRequest).setEntity(data);
        } else {
            throw new ZLNetworkException("Unknown request type");
        }
        httpRequest.setHeader("User-Agent", ZLNetworkUtil.getUserAgent());
        if (!request.isQuiet()) {
            httpRequest.setHeader("X-Accept-Auto-Login", "True");
        }
        httpRequest.setHeader("Accept-Encoding", "gzip");
        httpRequest.setHeader("Accept-Language", ZLResource.getLanguage());
        for (Map.Entry<String, String> header : request.Headers.entrySet()) {
            httpRequest.setHeader(header.getKey(), header.getValue());
        }
        httpClient.setCredentialsProvider(new MyCredentialsProvider(httpRequest, request.isQuiet()));
        final HttpResponse response = execute(httpClient, httpRequest, httpContext, authenticator);
        entity = response.getEntity();
        if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
            final AuthState state = (AuthState) httpContext.getAttribute(ClientContext.TARGET_AUTH_STATE);
            if (state != null) {
                final AuthScopeKey key = new AuthScopeKey(state.getAuthScope());
                if (myCredentialsCreator.removeCredentials(key)) {
                    entity = null;
                }
            }
        }
        final int responseCode = response.getStatusLine().getStatusCode();
        InputStream stream = null;
        if (entity != null && (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_PARTIAL)) {
            stream = entity.getContent();
        }
        if (stream != null) {
            try {
                final Header encoding = entity.getContentEncoding();
                if (encoding != null && "gzip".equalsIgnoreCase(encoding.getValue())) {
                    stream = new GZIPInputStream(stream);
                }
                request.handleStream(stream, (int) entity.getContentLength());
            } finally {
                stream.close();
            }
            success = true;
        } else {
            if (responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
                throw new ZLNetworkAuthenticationException();
            } else {
                throw new ZLNetworkException(response.getStatusLine().toString());
            }
        }
    } catch (ZLNetworkException e) {
        throw e;
    } catch (IOException e) {
        e.printStackTrace();
        final String code;
        if (e instanceof UnknownHostException) {
            code = ZLNetworkException.ERROR_RESOLVE_HOST;
        } else {
            code = ZLNetworkException.ERROR_CONNECT_TO_HOST;
        }
        throw ZLNetworkException.forCode(code, ZLNetworkUtil.hostFromUrl(request.URL), e);
    } catch (Exception e) {
        e.printStackTrace();
        throw new ZLNetworkException(e.getMessage(), e);
    } finally {
        request.doAfter(success);
        if (httpClient != null) {
            httpClient.getConnectionManager().shutdown();
        }
        if (entity != null) {
            try {
                entity.consumeContent();
            } catch (IOException e) {
            }
        }
    }
}
Also used : BasicHttpContext(org.apache.http.protocol.BasicHttpContext) GZIPInputStream(java.util.zip.GZIPInputStream) StringEntity(org.apache.http.entity.StringEntity) MultipartEntity(org.apache.http.entity.mime.MultipartEntity) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) AuthenticationHandler(org.apache.http.client.AuthenticationHandler) FileBody(org.apache.http.entity.mime.content.FileBody) GZIPInputStream(java.util.zip.GZIPInputStream) BasicHttpContext(org.apache.http.protocol.BasicHttpContext) HttpContext(org.apache.http.protocol.HttpContext) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity)

Example 20 with MultipartEntity

use of org.apache.http.entity.mime.MultipartEntity in project undertow by undertow-io.

the class MultipartFormDataParserTestCase method testFileUpload.

@Test
public void testFileUpload() throws Exception {
    DefaultServer.setRootHandler(new BlockingHandler(createHandler()));
    TestHttpClient client = new TestHttpClient();
    try {
        HttpPost post = new HttpPost(DefaultServer.getDefaultServerURL() + "/path");
        // post.setHeader(Headers.CONTENT_TYPE, MultiPartHandler.MULTIPART_FORM_DATA);
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        entity.addPart("formValue", new StringBody("myValue", "text/plain", StandardCharsets.UTF_8));
        entity.addPart("file", new FileBody(new File(MultipartFormDataParserTestCase.class.getResource("uploadfile.txt").getFile())));
        post.setEntity(entity);
        HttpResponse result = client.execute(post);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        HttpClientUtils.readResponse(result);
    } finally {
        client.getConnectionManager().shutdown();
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) FileBody(org.apache.http.entity.mime.content.FileBody) BlockingHandler(io.undertow.server.handlers.BlockingHandler) MultipartEntity(org.apache.http.entity.mime.MultipartEntity) StringBody(org.apache.http.entity.mime.content.StringBody) HttpResponse(org.apache.http.HttpResponse) File(java.io.File) TestHttpClient(io.undertow.testutils.TestHttpClient) Test(org.junit.Test)

Aggregations

MultipartEntity (org.apache.http.entity.mime.MultipartEntity)62 HttpPost (org.apache.http.client.methods.HttpPost)41 StringBody (org.apache.http.entity.mime.content.StringBody)40 FileBody (org.apache.http.entity.mime.content.FileBody)37 File (java.io.File)31 HttpResponse (org.apache.http.HttpResponse)28 Test (org.junit.Test)24 TestHttpClient (io.undertow.testutils.TestHttpClient)13 IOException (java.io.IOException)13 InputStreamBody (org.apache.http.entity.mime.content.InputStreamBody)7 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)7 JSONObject (org.json.JSONObject)7 HashMap (java.util.HashMap)5 Map (java.util.Map)5 HttpEntity (org.apache.http.HttpEntity)5 ByteArrayBody (org.apache.http.entity.mime.content.ByteArrayBody)5 RequestBuilder (org.apache.sling.testing.tools.http.RequestBuilder)5 JSONException (org.json.JSONException)5 BlockingHandler (io.undertow.server.handlers.BlockingHandler)4 InputStream (java.io.InputStream)4