Search in sources :

Example 56 with StringBody

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

the class ParameterCharacterEncodingTestCase method testMultipartCharacterEncoding.

@Test
public void testMultipartCharacterEncoding() throws IOException {
    TestHttpClient client = new TestHttpClient();
    try {
        String message = "abcčšž";
        String charset = "UTF-8";
        HttpPost post = new HttpPost(DefaultServer.getDefaultServerURL() + "/servletContext");
        MultipartEntity multipart = new MultipartEntity();
        multipart.addPart("charset", new StringBody(charset, Charset.forName(charset)));
        multipart.addPart("message", new StringBody(message, Charset.forName(charset)));
        post.setEntity(multipart);
        HttpResponse result = client.execute(post);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        String response = HttpClientUtils.readResponse(result);
        Assert.assertEquals(message, response);
    } finally {
        client.getConnectionManager().shutdown();
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) MultipartEntity(org.apache.http.entity.mime.MultipartEntity) StringBody(org.apache.http.entity.mime.content.StringBody) HttpResponse(org.apache.http.HttpResponse) TestHttpClient(io.undertow.testutils.TestHttpClient) Test(org.junit.Test)

Example 57 with StringBody

use of org.apache.http.entity.mime.content.StringBody in project AndroidSDK-RecipeBook by gabu.

the class Recipe095 method uploadForTumblr.

// 指定されたUriの写真をTumblrにアップロードします。
private void uploadForTumblr(Uri uri) {
    // HTTPクライアントを作って
    HttpClient client = new DefaultHttpClient();
    // POST先のURLを指定してPOSTオブジェクトを作って
    HttpPost post = new HttpPost("http://www.tumblr.com/api/write");
    // パラメータを作って
    MultipartEntity entity = new MultipartEntity();
    try {
        // Thumblrに登録したメールアドレス
        entity.addPart("email", new StringBody("hoge@example.com"));
        // Thumblrに登録したパスワード
        entity.addPart("password", new StringBody("1234"));
        // 投稿する種類。今回は写真なのでphoto
        entity.addPart("type", new StringBody("photo"));
        // 写真データ
        entity.addPart("data", new InputStreamBody(getContentResolver().openInputStream(uri), "filename"));
        // POSTオブジェクトにパラメータをセット
        post.setEntity(entity);
        // POSTリクエストを実行
        client.execute(post);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) MultipartEntity(org.apache.http.entity.mime.MultipartEntity) StringBody(org.apache.http.entity.mime.content.StringBody) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) FileNotFoundException(java.io.FileNotFoundException) InputStreamBody(org.apache.http.entity.mime.content.InputStreamBody) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) ClientProtocolException(org.apache.http.client.ClientProtocolException)

Example 58 with StringBody

use of org.apache.http.entity.mime.content.StringBody in project OpenRefine by OpenRefine.

the class ImportingUtilitiesTests method urlImporting.

@Test
public void urlImporting() throws IOException {
    String RESPONSE_BODY = "{code:401,message:Unauthorised}";
    MockWebServer server = new MockWebServer();
    MockResponse mockResponse = new MockResponse();
    mockResponse.setBody(RESPONSE_BODY);
    mockResponse.setResponseCode(401);
    server.start();
    server.enqueue(mockResponse);
    HttpUrl url = server.url("/random");
    String MESSAGE = String.format("HTTP error %d : %s for URL %s", 401, "Client Error", url);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    StringBody stringBody = new StringBody(url.toString(), ContentType.MULTIPART_FORM_DATA);
    builder = builder.addPart("download", stringBody);
    HttpEntity entity = builder.build();
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    entity.writeTo(os);
    ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
    HttpServletRequest req = mock(HttpServletRequest.class);
    when(req.getContentType()).thenReturn(entity.getContentType().getValue());
    when(req.getParameter("download")).thenReturn(url.toString());
    when(req.getMethod()).thenReturn("POST");
    when(req.getContentLength()).thenReturn((int) entity.getContentLength());
    when(req.getInputStream()).thenReturn(new MockServletInputStream(is));
    ImportingJob job = ImportingManager.createJob();
    Properties parameters = ParsingUtilities.parseUrlParameters(req);
    ObjectNode retrievalRecord = ParsingUtilities.mapper.createObjectNode();
    ObjectNode progress = ParsingUtilities.mapper.createObjectNode();
    try {
        ImportingUtilities.retrieveContentFromPostRequest(req, parameters, job.getRawDataDir(), retrievalRecord, new ImportingUtilities.Progress() {

            @Override
            public void setProgress(String message, int percent) {
                if (message != null) {
                    JSONUtilities.safePut(progress, "message", message);
                }
                JSONUtilities.safePut(progress, "percent", percent);
            }

            @Override
            public boolean isCanceled() {
                return job.canceled;
            }
        });
        fail("No Exception was thrown");
    } catch (Exception exception) {
        assertEquals(exception.getMessage(), MESSAGE);
    } finally {
        server.close();
    }
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) Progress(com.google.refine.importing.ImportingUtilities.Progress) MultipartEntityBuilder(org.apache.http.entity.mime.MultipartEntityBuilder) HttpEntity(org.apache.http.HttpEntity) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Properties(java.util.Properties) HttpUrl(okhttp3.HttpUrl) IOException(java.io.IOException) HttpServletRequest(javax.servlet.http.HttpServletRequest) StringBody(org.apache.http.entity.mime.content.StringBody) ByteArrayInputStream(java.io.ByteArrayInputStream) MockWebServer(okhttp3.mockwebserver.MockWebServer) ImporterTest(com.google.refine.importers.ImporterTest) Test(org.testng.annotations.Test)

Example 59 with StringBody

use of org.apache.http.entity.mime.content.StringBody in project BIMserver by opensourceBIM.

the class Channel method bulkCheckin.

public void bulkCheckin(String baseAddress, String token, long poid, String comment, Path file) throws UserException, ServerException {
    String address = baseAddress + "/bulkupload";
    HttpPost httppost = new HttpPost(address);
    try (InputStream inputStream = Files.newInputStream(file)) {
        InputStreamBody data = new InputStreamBody(inputStream, file.getFileName().toString());
        MultipartEntityBuilder multipartEntityBuilder = createMultiPart();
        multipartEntityBuilder.addPart("token", new StringBody(token, ContentType.DEFAULT_TEXT));
        multipartEntityBuilder.addPart("poid", new StringBody("" + poid, ContentType.DEFAULT_TEXT));
        multipartEntityBuilder.addPart("comment", new StringBody("" + comment, ContentType.DEFAULT_TEXT));
        multipartEntityBuilder.addPart("data", data);
        httppost.setEntity(multipartEntityBuilder.build());
        HttpResponse httpResponse = closeableHttpClient.execute(httppost);
        if (httpResponse.getStatusLine().getStatusCode() == 200) {
            ObjectMapper objectMapper = new ObjectMapper();
            InputStreamReader in = new InputStreamReader(httpResponse.getEntity().getContent());
            try {
                ObjectNode result = objectMapper.readValue(in, ObjectNode.class);
                if (result.has("exception")) {
                    ObjectNode exceptionJson = (ObjectNode) result.get("exception");
                    String exceptionType = exceptionJson.get("__type").asText();
                    String message = exceptionJson.has("message") ? exceptionJson.get("message").asText() : "unknown";
                    if (exceptionType.equals(UserException.class.getSimpleName())) {
                        throw new UserException(message);
                    } else if (exceptionType.equals(ServerException.class.getSimpleName())) {
                        throw new ServerException(message);
                    }
                }
            } finally {
                in.close();
            }
        }
    } catch (ClientProtocolException e) {
        throw new ServerException(e);
    } catch (IOException e) {
        throw new ServerException(e);
    } catch (PublicInterfaceNotFoundException e) {
        throw new ServerException(e);
    } finally {
        httppost.releaseConnection();
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) MultipartEntityBuilder(org.apache.http.entity.mime.MultipartEntityBuilder) ServerException(org.bimserver.shared.exceptions.ServerException) InputStreamReader(java.io.InputStreamReader) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) DeflaterInputStream(java.util.zip.DeflaterInputStream) InputStream(java.io.InputStream) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) ClientProtocolException(org.apache.http.client.ClientProtocolException) StringBody(org.apache.http.entity.mime.content.StringBody) PublicInterfaceNotFoundException(org.bimserver.shared.exceptions.PublicInterfaceNotFoundException) InputStreamBody(org.apache.http.entity.mime.content.InputStreamBody) UserException(org.bimserver.shared.exceptions.UserException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 60 with StringBody

use of org.apache.http.entity.mime.content.StringBody in project BIMserver by opensourceBIM.

the class Channel method checkinAsync.

public long checkinAsync(String baseAddress, String token, long poid, String comment, long deserializerOid, boolean merge, long fileSize, String filename, InputStream inputStream, long topicId) throws ServerException, UserException {
    String address = baseAddress + "/upload";
    HttpPost httppost = new HttpPost(address);
    try {
        // TODO find some GzipInputStream variant that _compresses_ instead
        // of _decompresses_ using deflate for now
        InputStreamBody data = new InputStreamBody(new DeflaterInputStream(inputStream), filename);
        MultipartEntityBuilder multipartEntityBuilder = createMultiPart();
        multipartEntityBuilder.addPart("topicId", new StringBody("" + topicId, ContentType.DEFAULT_TEXT));
        multipartEntityBuilder.addPart("token", new StringBody(token, ContentType.DEFAULT_TEXT));
        multipartEntityBuilder.addPart("deserializerOid", new StringBody("" + deserializerOid, ContentType.DEFAULT_TEXT));
        multipartEntityBuilder.addPart("merge", new StringBody("" + merge, ContentType.DEFAULT_TEXT));
        multipartEntityBuilder.addPart("poid", new StringBody("" + poid, ContentType.DEFAULT_TEXT));
        multipartEntityBuilder.addPart("comment", new StringBody("" + comment, ContentType.DEFAULT_TEXT));
        multipartEntityBuilder.addPart("sync", new StringBody("" + false, ContentType.DEFAULT_TEXT));
        multipartEntityBuilder.addPart("compression", new StringBody("deflate", ContentType.DEFAULT_TEXT));
        multipartEntityBuilder.addPart("data", data);
        httppost.setEntity(multipartEntityBuilder.build());
        HttpResponse httpResponse = closeableHttpClient.execute(httppost);
        if (httpResponse.getStatusLine().getStatusCode() == 200) {
            ObjectMapper objectMapper = new ObjectMapper();
            InputStreamReader in = new InputStreamReader(httpResponse.getEntity().getContent());
            try {
                ObjectNode result = objectMapper.readValue(in, ObjectNode.class);
                if (result.has("exception")) {
                    ObjectNode exceptionJson = (ObjectNode) result.get("exception");
                    String exceptionType = exceptionJson.get("__type").asText();
                    String message = exceptionJson.has("message") ? exceptionJson.get("message").asText() : "unknown";
                    if (exceptionType.equals(UserException.class.getSimpleName())) {
                        throw new UserException(message);
                    } else if (exceptionType.equals(ServerException.class.getSimpleName())) {
                        throw new ServerException(message);
                    }
                } else {
                    if (result.has("topicId")) {
                        return result.get("topicId").asLong();
                    } else {
                        throw new ServerException("No topicId found in response: " + result.toString());
                    }
                }
            } finally {
                in.close();
            }
        }
    } catch (ClientProtocolException e) {
        throw new ServerException(e);
    } catch (IOException e) {
        throw new ServerException(e);
    } catch (PublicInterfaceNotFoundException e) {
        throw new ServerException(e);
    } finally {
        httppost.releaseConnection();
    }
    return -1;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) MultipartEntityBuilder(org.apache.http.entity.mime.MultipartEntityBuilder) ServerException(org.bimserver.shared.exceptions.ServerException) InputStreamReader(java.io.InputStreamReader) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) DeflaterInputStream(java.util.zip.DeflaterInputStream) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) ClientProtocolException(org.apache.http.client.ClientProtocolException) StringBody(org.apache.http.entity.mime.content.StringBody) PublicInterfaceNotFoundException(org.bimserver.shared.exceptions.PublicInterfaceNotFoundException) InputStreamBody(org.apache.http.entity.mime.content.InputStreamBody) UserException(org.bimserver.shared.exceptions.UserException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Aggregations

StringBody (org.apache.http.entity.mime.content.StringBody)72 HttpPost (org.apache.http.client.methods.HttpPost)50 MultipartEntity (org.apache.http.entity.mime.MultipartEntity)42 HttpResponse (org.apache.http.HttpResponse)33 FileBody (org.apache.http.entity.mime.content.FileBody)31 File (java.io.File)26 Test (org.junit.Test)25 HttpEntity (org.apache.http.HttpEntity)24 IOException (java.io.IOException)19 MultipartEntityBuilder (org.apache.http.entity.mime.MultipartEntityBuilder)18 TestHttpClient (io.undertow.testutils.TestHttpClient)14 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)8 InputStreamReader (java.io.InputStreamReader)7 HttpClient (org.apache.http.client.HttpClient)7 InputStreamBody (org.apache.http.entity.mime.content.InputStreamBody)7 Header (org.apache.http.Header)6 ClientProtocolException (org.apache.http.client.ClientProtocolException)6 InputStream (java.io.InputStream)5 HashMap (java.util.HashMap)5 Map (java.util.Map)5