Search in sources :

Example 66 with StringBody

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

the class HttpServerTest method testMultipartFormData.

@Test
public void testMultipartFormData() throws IOException {
    final int testPort = 4589;
    NanoHTTPD server = null;
    try {
        server = new NanoHTTPD(testPort) {

            final Map<String, String> files = new HashMap<String, String>();

            @Override
            public Response serve(IHTTPSession session) {
                StringBuilder responseMsg = new StringBuilder();
                try {
                    session.parseBody(this.files);
                    for (String key : files.keySet()) {
                        responseMsg.append(key);
                    }
                } catch (Exception e) {
                    responseMsg.append(e.getMessage());
                }
                return Response.newFixedLengthResponse(responseMsg.toString());
            }
        };
        server.start(NanoHTTPD.SOCKET_READ_TIMEOUT, false);
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://localhost:" + testPort);
        final String fileName = "file-upload-test.htm";
        FileBody bin = new FileBody(new File(getClass().getClassLoader().getResource(fileName).getFile()));
        StringBody comment = new StringBody("Filename: " + fileName);
        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart("bin", bin);
        reqEntity.addPart("comment", comment);
        httppost.setEntity(reqEntity);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream instream = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(instream, "UTF-8"));
            String line = reader.readLine();
            assertNotNull(line, "Invalid server reponse");
            assertEquals("Server failed multi-part data parse" + line, "bincomment", line);
            reader.close();
            instream.close();
        }
    } finally {
        if (server != null) {
            server.stop();
        }
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) FileBody(org.apache.http.entity.mime.content.FileBody) HttpEntity(org.apache.http.HttpEntity) InputStreamReader(java.io.InputStreamReader) HashMap(java.util.HashMap) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) NanoHTTPD(org.nanohttpd.protocols.http.NanoHTTPD) HttpResponse(org.apache.http.HttpResponse) IHTTPSession(org.nanohttpd.protocols.http.IHTTPSession) IOException(java.io.IOException) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) Response(org.nanohttpd.protocols.http.response.Response) HttpResponse(org.apache.http.HttpResponse) StringBody(org.apache.http.entity.mime.content.StringBody) MultipartEntity(org.apache.http.entity.mime.MultipartEntity) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) BufferedReader(java.io.BufferedReader) File(java.io.File) Test(org.junit.Test)

Example 67 with StringBody

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

the class HttpServerTest method testTempFileInterface.

@Test
public void testTempFileInterface() throws IOException {
    final int testPort = 4589;
    NanoHTTPD server = new NanoHTTPD(testPort) {

        final Map<String, String> files = new HashMap<String, String>();

        @Override
        public Response serve(IHTTPSession session) {
            String responseMsg = "pass";
            try {
                session.parseBody(this.files);
                for (String key : files.keySet()) {
                    if (!(new File(files.get(key))).exists()) {
                        responseMsg = "fail";
                    }
                }
            } catch (Exception e) {
                responseMsg = e.getMessage();
            }
            return Response.newFixedLengthResponse(responseMsg.toString());
        }
    };
    server.start(NanoHTTPD.SOCKET_READ_TIMEOUT, false);
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://localhost:" + testPort);
    final String fileName = "file-upload-test.htm";
    FileBody bin = new FileBody(new File(getClass().getClassLoader().getResource(fileName).getFile()));
    StringBody comment = new StringBody("Filename: " + fileName);
    MultipartEntity reqEntity = new MultipartEntity();
    reqEntity.addPart("bin", bin);
    reqEntity.addPart("comment", comment);
    httppost.setEntity(reqEntity);
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        InputStream instream = entity.getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(instream, "UTF-8"));
        String line = reader.readLine();
        assertNotNull(line, "Invalid server reponse");
        assertEquals("Server file check failed: " + line, "pass", line);
        reader.close();
        instream.close();
    } else {
        fail("No server response");
    }
    server.stop();
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) FileBody(org.apache.http.entity.mime.content.FileBody) HttpEntity(org.apache.http.HttpEntity) InputStreamReader(java.io.InputStreamReader) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) NanoHTTPD(org.nanohttpd.protocols.http.NanoHTTPD) HttpResponse(org.apache.http.HttpResponse) IHTTPSession(org.nanohttpd.protocols.http.IHTTPSession) IOException(java.io.IOException) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) StringBody(org.apache.http.entity.mime.content.StringBody) MultipartEntity(org.apache.http.entity.mime.MultipartEntity) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) BufferedReader(java.io.BufferedReader) HashMap(java.util.HashMap) Map(java.util.Map) File(java.io.File) Test(org.junit.Test)

Example 68 with StringBody

use of org.apache.http.entity.mime.content.StringBody in project streamsx.topology by IBMStreams.

the class AbstractStreamingAnalyticsService method postJob.

/**
 * Submit an application bundle to execute as a job.
 */
protected JsonObject postJob(CloseableHttpClient httpClient, JsonObject service, File bundle, JsonObject jobConfigOverlay) throws IOException {
    String url = getJobSubmitUrl(httpClient, bundle);
    HttpPost postJobWithConfig = new HttpPost(url);
    postJobWithConfig.addHeader(AUTH.WWW_AUTH_RESP, getAuthorization());
    FileBody bundleBody = new FileBody(bundle, ContentType.APPLICATION_OCTET_STREAM);
    StringBody configBody = new StringBody(jobConfigOverlay.toString(), ContentType.APPLICATION_JSON);
    HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("bundle_file", bundleBody).addPart("job_options", configBody).build();
    postJobWithConfig.setEntity(reqEntity);
    JsonObject jsonResponse = StreamsRestUtils.getGsonResponse(httpClient, postJobWithConfig);
    TRACE.info("Streaming Analytics service (" + getName() + "): submit job response:" + jsonResponse.toString());
    return jsonResponse;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) FileBody(org.apache.http.entity.mime.content.FileBody) HttpEntity(org.apache.http.HttpEntity) StringBody(org.apache.http.entity.mime.content.StringBody) JsonObject(com.google.gson.JsonObject)

Example 69 with StringBody

use of org.apache.http.entity.mime.content.StringBody in project streamsx.topology by IBMStreams.

the class StreamingAnalyticsServiceV2 method submitBuild.

@Override
protected JsonObject submitBuild(CloseableHttpClient httpclient, File archive, String buildName, String originator) throws IOException {
    String newBuildURL = getBuildsUrl(httpclient);
    newBuildURL = newBuildURL + "?originator=" + URLEncoder.encode(originator, StandardCharsets.UTF_8.name());
    HttpPost httppost = new HttpPost(newBuildURL);
    httppost.addHeader("Authorization", getAuthorization());
    JsonObject buildParams = new JsonObject();
    buildParams.addProperty("buildName", buildName);
    StringBody paramsBody = new StringBody(buildParams.toString(), ContentType.APPLICATION_JSON);
    FileBody archiveBody = new FileBody(archive, ContentType.create("application/zip"), archive.getName());
    HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("build_options", paramsBody).addPart("archive_file", archiveBody).build();
    httppost.setEntity(reqEntity);
    JsonObject build = StreamsRestUtils.getGsonResponse(httpclient, httppost);
    return build;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) FileBody(org.apache.http.entity.mime.content.FileBody) HttpEntity(org.apache.http.HttpEntity) StringBody(org.apache.http.entity.mime.content.StringBody) JsonObject(com.google.gson.JsonObject)

Example 70 with StringBody

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

the class FileHandlingHttpRequestExecuterImpl method postData.

@Override
public HttpResponse postData(String url, Hashtable getParams, Hashtable postParams) throws HttpRequestException {
    // test to determine whether this is a file upload or not.
    Boolean isFileUpload = false;
    for (Object o : postParams.values()) {
        if (o instanceof File) {
            isFileUpload = true;
            break;
        }
    }
    if (isFileUpload) {
        try {
            HttpPost httpPost = new HttpPost(createUrl(url, getParams));
            httpPost.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
            MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
            for (Object o : postParams.entrySet()) {
                Map.Entry<String, Object> entry = (Map.Entry<String, Object>) o;
                if (entry.getValue() instanceof File) {
                    // For File parameters
                    File file = (File) entry.getValue();
                    FileNameMap fileNameMap = URLConnection.getFileNameMap();
                    String type = fileNameMap.getContentTypeFor(file.toURL().toString());
                    entity.addPart(entry.getKey(), new FileBody(((File) entry.getValue()), type));
                } else {
                    // For usual String parameters
                    entity.addPart(entry.getKey(), new StringBody(entry.getValue().toString(), "text/plain", Charset.forName(FormConstants.CHAR_ENC_DEFAULT)));
                }
            }
            httpPost.setEntity(entity);
            return execute(httpPost);
        } catch (Exception e) {
            throw new HttpRequestException(e);
        }
    } else {
        return super.postData(url, getParams, postParams);
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) FileBody(org.apache.http.entity.mime.content.FileBody) FileNameMap(java.net.FileNameMap) MultipartEntity(org.apache.http.entity.mime.MultipartEntity) StringBody(org.apache.http.entity.mime.content.StringBody) File(java.io.File) FileNameMap(java.net.FileNameMap) Map(java.util.Map)

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