Example usage for org.apache.http.entity.mime.content FileBody getFilename

List of usage examples for org.apache.http.entity.mime.content FileBody getFilename

Introduction

In this page you can find the example usage for org.apache.http.entity.mime.content FileBody getFilename.

Prototype

public String getFilename() 

Source Link

Usage

From source file:core.AbstractTest.java

private int httpRequest(String sUrl, String sMethod, JsonNode payload, Map<String, String> mParameters) {
    Logger.info("\n\nREQUEST:\n" + sMethod + " " + sUrl + "\nHEADERS: " + mHeaders + "\nParameters: "
            + mParameters + "\nPayload: " + payload + "\n");
    HttpURLConnection conn = null;
    BufferedReader br = null;/* ww w. j a  v a 2 s .c  om*/
    int nRet = 0;
    boolean fIsMultipart = false;

    try {
        setStatusCode(-1);
        setResponse(null);
        conn = getHttpConnection(sUrl, sMethod);
        if (mHeaders.size() > 0) {
            Set<String> keys = mHeaders.keySet();
            for (String sKey : keys) {
                conn.addRequestProperty(sKey, mHeaders.get(sKey));
                if (sKey.equals(HTTP.CONTENT_TYPE)) {
                    if (mHeaders.get(sKey).startsWith(MediaType.MULTIPART_FORM_DATA)) {
                        fIsMultipart = true;
                    }
                }
            }
        }

        if (payload != null || mParameters != null) {
            DataOutputStream out = new DataOutputStream(conn.getOutputStream());

            try {
                if (payload != null) {
                    //conn.setRequestProperty("Content-Length", "" + node.toString().length());
                    out.writeBytes(payload.toString());
                }

                if (mParameters != null) {
                    Set<String> sKeys = mParameters.keySet();

                    if (fIsMultipart) {
                        out.writeBytes("--" + BOUNDARY + "\r\n");
                    }

                    for (String sKey : sKeys) {
                        if (fIsMultipart) {
                            out.writeBytes("Content-Disposition: form-data; name=\"" + sKey + "\"\r\n\r\n");
                            out.writeBytes(mParameters.get(sKey));
                            out.writeBytes("\r\n");
                            out.writeBytes("--" + BOUNDARY + "--\r\n");
                        } else {
                            out.writeBytes(URLEncoder.encode(sKey, "UTF-8"));
                            out.writeBytes("=");
                            out.writeBytes(URLEncoder.encode(mParameters.get(sKey), "UTF-8"));
                            out.writeBytes("&");
                        }
                    }

                    if (fIsMultipart) {
                        if (nvpFile != null) {
                            File f = Play.application().getFile(nvpFile.getName());
                            if (f == null) {
                                assertFail("Cannot find file <" + nvpFile.getName() + ">");
                            }
                            FileBody fb = new FileBody(f);
                            out.writeBytes("Content-Disposition: form-data; name=\"" + PARAM_FILE
                                    + "\";filename=\"" + fb.getFilename() + "\"\r\n");
                            out.writeBytes("Content-Type: " + nvpFile.getValue() + "\r\n\r\n");
                            out.write(getResource(nvpFile.getName()));
                        }
                        out.writeBytes("\r\n--" + BOUNDARY + "--\r\n");
                    }
                }
            } catch (Exception ex) {
                assertFail("Send request: " + ex.getMessage());
            } finally {
                try {
                    out.flush();
                } catch (Exception ex) {
                }
                try {
                    out.close();
                } catch (Exception ex) {
                }
            }
        }

        nRet = conn.getResponseCode();
        setStatusCode(nRet);
        if (nRet / 100 != 2) {
            if (conn.getErrorStream() != null) {
                br = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
            }
        } else {
            if (conn.getInputStream() != null) {
                br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            }
        }

        if (br != null) {
            String temp = null;
            StringBuilder sb = new StringBuilder(1024);
            while ((temp = br.readLine()) != null) {
                sb.append(temp).append("\n");
            }
            setResponse(sb.toString().trim());
        }
        Logger.info("\nRESPONSE\nHTTP code: " + nRet + "\nContent: " + sResponse + "\n");
    } catch (Exception ex) {
        assertFail("httpRequest: " + ex.getMessage());
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (Exception ex) {
            }
        }
        if (conn != null) {
            conn.disconnect();
        }
    }

    return nRet;
}

From source file:com.devbliss.doctest.LogicDocTest.java

protected ApiResponse makePostUploadRequest(URI uri, File fileToUpload, String paramName,
        Map<String, String> additionalHeaders) throws Exception {
    FileBody fileBodyToUpload = new FileBody(fileToUpload);
    String mimeType = new MimetypesFileTypeMap().getContentType(fileToUpload);

    Context context = apiTest.post(uri, null, new PostUploadWithoutRedirectImpl(paramName, fileBodyToUpload),
            additionalHeaders);//from ww  w .j a v  a 2  s.  c o m

    docTestMachine.sayUploadRequest(context.apiRequest, fileBodyToUpload.getFilename(),
            fileHelper.readFile(fileToUpload), fileToUpload.length(), mimeType, headersToShow, cookiesToShow);

    docTestMachine.sayResponse(context.apiResponse, headersToShow);

    return context.apiResponse;
}

From source file:com.att.api.rest.RESTClient.java

/**
 * Sends an http POST multipart request.
 *
 * @param jsonObj JSON Object to set as the start part
 * @param fnames file names for any files to add
 * @return api response//from   w w  w  .ja  v a 2s  . com
 *
 * @throws RESTException if request was unsuccessful
 */
public APIResponse httpPost(JSONObject jsonObj, String[] fnames) throws RESTException {

    HttpResponse response = null;
    try {
        HttpClient httpClient = createClient();

        HttpPost httpPost = new HttpPost(url);
        this.setHeader("Content-Type",
                "multipart/form-data; type=\"application/json\"; " + "start=\"<startpart>\"; boundary=\"foo\"");
        addInternalHeaders(httpPost);

        final Charset encoding = Charset.forName("UTF-8");
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.STRICT, "foo", encoding);
        StringBody sbody = new StringBody(jsonObj.toString(), "application/json", encoding);
        FormBodyPart stringBodyPart = new FormBodyPart("root-fields", sbody);
        stringBodyPart.addField("Content-ID", "<startpart>");
        entity.addPart(stringBodyPart);

        for (int i = 0; i < fnames.length; ++i) {
            final String fname = fnames[i];
            String type = URLConnection.guessContentTypeFromStream(new FileInputStream(fname));

            if (type == null) {
                type = URLConnection.guessContentTypeFromName(fname);
            }
            if (type == null) {
                type = "application/octet-stream";
            }

            FileBody fb = new FileBody(new File(fname), type, "UTF-8");
            FormBodyPart fileBodyPart = new FormBodyPart(fb.getFilename(), fb);

            fileBodyPart.addField("Content-ID", "<fileattachment" + i + ">");

            fileBodyPart.addField("Content-Location", fb.getFilename());
            entity.addPart(fileBodyPart);
        }
        httpPost.setEntity(entity);
        return buildResponse(httpClient.execute(httpPost));
    } catch (Exception e) {
        throw new RESTException(e);
    } finally {
        if (response != null) {
            this.releaseConnection(response);
        }
    }
}

From source file:com.att.api.rest.RESTClient.java

public APIResponse httpPost(String[] fnames, String subType, String[] bodyNameAttribute) throws RESTException {
    HttpResponse response = null;/*  w  w w  .jav  a2s  .c  o m*/
    try {
        HttpClient httpClient = createClient();

        HttpPost httpPost = new HttpPost(url);
        this.setHeader("Content-Type", "multipart/" + subType + "; " + "boundary=\"foo\"");
        addInternalHeaders(httpPost);

        final Charset encoding = Charset.forName("UTF-8");
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.STRICT, "foo", encoding);

        for (int i = 0; i < fnames.length; ++i) {
            final String fname = fnames[i];
            String contentType = null;
            contentType = URLConnection.guessContentTypeFromStream(new FileInputStream(fname));
            if (contentType == null) {
                contentType = URLConnection.guessContentTypeFromName(fname);
            }
            if (contentType == null)
                contentType = this.getMIMEType(new File(fname));
            if (fname.endsWith("srgs"))
                contentType = "application/srgs+xml";
            if (fname.endsWith("grxml"))
                contentType = "application/srgs+xml";
            if (fname.endsWith("pls"))
                contentType = "application/pls+xml";
            FileBody fb = new FileBody(new File(fname), contentType, "UTF-8");
            FormBodyPart fileBodyPart = new FormBodyPart(bodyNameAttribute[i], fb);
            fileBodyPart.addField("Content-ID", "<fileattachment" + i + ">");
            fileBodyPart.addField("Content-Location", fb.getFilename());
            if (contentType != null) {
                fileBodyPart.addField("Content-Type", contentType);
            }
            entity.addPart(fileBodyPart);
        }
        httpPost.setEntity(entity);
        return buildResponse(httpClient.execute(httpPost));
    } catch (IOException e) {
        throw new RESTException(e);
    } finally {
        if (response != null) {
            this.releaseConnection(response);
        }
    }
}