Example usage for org.apache.http.entity.mime.content StringBody StringBody

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

Introduction

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

Prototype

public StringBody(final String text) throws UnsupportedEncodingException 

Source Link

Usage

From source file:com.mutu.gpstracker.breadcrumbs.UploadBreadcrumbsTrackTask.java

private void uploadPhoto(File photo, Integer trackId) throws IOException, OAuthMessageSignerException,
        OAuthExpectationFailedException, OAuthCommunicationException {
    HttpPost request = new HttpPost("http://api.gobreadcrumbs.com/v1/photos.xml");
    if (isCancelled()) {
        throw new IOException("Fail to execute request due to canceling");
    }// ww w .jav a  2  s. co m

    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    entity.addPart("name", new StringBody(photo.getName()));
    entity.addPart("track_id", new StringBody(Integer.toString(trackId)));
    //entity.addPart("description", new StringBody(""));
    entity.addPart("file", new FileBody(photo));
    request.setEntity(entity);

    mConsumer.sign(request);
    if (BreadcrumbsAdapter.DEBUG) {
        Log.d(TAG, "Execute request: " + request.getURI());
        for (Header header : request.getAllHeaders()) {
            Log.d(TAG, "   with header: " + header.toString());
        }
    }
    HttpResponse response = mHttpClient.execute(request);
    HttpEntity responseEntity = response.getEntity();
    InputStream stream = responseEntity.getContent();
    String responseText = XmlCreator.convertStreamToString(stream);

    mProgressAdmin.addPhotoUploadProgress(photo.length());

    Log.i(TAG, "Uploaded photo " + responseText);
}

From source file:org.wso2.am.integration.tests.publisher.APIM614AddDocumentationToAnAPIWithDocTypeSampleAndSDKThroughPublisherRestAPITestCase.java

@Test(groups = { "wso2.am" }, description = "Add Documentation To An API With Type  support forum And"
        + " Source File through the publisher rest API ", dependsOnMethods = "testAddDocumentToAnAPIPublicToFile")
public void testAddDocumentToAnAPISupportToFile() throws Exception {

    String fileNameAPIM626 = "APIM626.txt";
    String docName = "APIM626PublisherTestHowTo-File-summary";
    String docType = "support forum";
    String sourceType = "file";
    String summary = "Testing";
    String mimeType = "text/plain";
    String docUrl = "http://";
    String filePathAPIM626 = TestConfigurationProvider.getResourceLocation() + File.separator + "artifacts"
            + File.separator + "AM" + File.separator + "lifecycletest" + File.separator + fileNameAPIM626;
    String addDocUrl = publisherUrls.getWebAppURLHttp() + "publisher/site/blocks/documentation/ajax/docs.jag";

    //Send Http Post request to add a new file
    HttpPost httppost = new HttpPost(addDocUrl);
    File file = new File(filePathAPIM626);
    FileBody fileBody = new FileBody(file, "text/plain");

    //Create multipart entity to upload file as multipart file
    MultipartEntity multipartEntity = new MultipartEntity();
    multipartEntity.addPart("docLocation", fileBody);
    multipartEntity.addPart("mode", new StringBody(""));
    multipartEntity.addPart("docName", new StringBody(docName));
    multipartEntity.addPart("docUrl", new StringBody(docUrl));
    multipartEntity.addPart("sourceType", new StringBody(sourceType));
    multipartEntity.addPart("summary", new StringBody(summary));
    multipartEntity.addPart("docType", new StringBody(docType));
    multipartEntity.addPart("version", new StringBody(apiVersion));
    multipartEntity.addPart("apiName", new StringBody(apiName));
    multipartEntity.addPart("action", new StringBody("addDocumentation"));
    multipartEntity.addPart("provider", new StringBody(apiProvider));
    multipartEntity.addPart("mimeType", new StringBody(mimeType));
    multipartEntity.addPart("optionsRadios", new StringBody(docType));
    multipartEntity.addPart("optionsRadios1", new StringBody(sourceType));
    multipartEntity.addPart("optionsRadios1", new StringBody(sourceType));

    httppost.setEntity(multipartEntity);

    //Upload created file and validate
    HttpResponse response = httpClient.execute(httppost);
    HttpEntity entity = response.getEntity();
    JSONObject jsonObject1 = new JSONObject(EntityUtils.toString(entity));
    assertFalse(jsonObject1.getBoolean("error"), "Error when adding files to the API ");
}

From source file:org.mumod.util.HttpManager.java

private InputStream requestData(String url, ArrayList<NameValuePair> params, String attachmentParam,
        File attachment) throws IOException, MustardException, AuthException {

    URI uri;/* w w  w. j  a  va  2  s  .co m*/

    try {
        uri = new URI(url);
    } catch (URISyntaxException e) {
        throw new IOException("Invalid URL.");
    }
    if (MustardApplication.DEBUG)
        Log.d("HTTPManager", "Requesting " + uri);

    HttpPost post = new HttpPost(uri);

    HttpResponse response;

    // create the multipart request and add the parts to it 
    MultipartEntity requestContent = new MultipartEntity();
    long len = attachment.length();

    InputStream ins = new FileInputStream(attachment);
    InputStreamEntity ise = new InputStreamEntity(ins, -1L);
    byte[] data = EntityUtils.toByteArray(ise);

    String IMAGE_MIME = attachment.getName().toLowerCase().endsWith("png") ? IMAGE_MIME_PNG : IMAGE_MIME_JPG;
    requestContent.addPart(attachmentParam, new ByteArrayBody(data, IMAGE_MIME, attachment.getName()));

    if (params != null) {
        for (NameValuePair param : params) {
            len += param.getValue().getBytes().length;
            requestContent.addPart(param.getName(), new StringBody(param.getValue()));
        }
    }
    post.setEntity(requestContent);

    Log.d("Mustard", "Length: " + len);

    if (mHeaders != null) {
        Iterator<String> headKeys = mHeaders.keySet().iterator();
        while (headKeys.hasNext()) {
            String key = headKeys.next();
            post.setHeader(key, mHeaders.get(key));
        }
    }

    if (consumer != null) {
        try {
            consumer.sign(post);
        } catch (OAuthMessageSignerException e) {

        } catch (OAuthExpectationFailedException e) {

        } catch (OAuthCommunicationException e) {

        }
    }

    try {
        mClient.getParams().setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT,
                DEFAULT_POST_REQUEST_TIMEOUT);
        mClient.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT, DEFAULT_POST_REQUEST_TIMEOUT);
        response = mClient.execute(post);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        throw new IOException("HTTP protocol error.");
    }

    int statusCode = response.getStatusLine().getStatusCode();

    if (statusCode == 401) {
        throw new AuthException(401, "Unauthorized: " + url);
    } else if (statusCode == 400 || statusCode == 403 || statusCode == 406) {
        try {
            JSONObject json = null;
            try {
                json = new JSONObject(StreamUtil.toString(response.getEntity().getContent()));
            } catch (JSONException e) {
                throw new MustardException(998, "Non json response: " + e.toString());
            }
            throw new MustardException(statusCode, json.getString("error"));
        } catch (IllegalStateException e) {
            throw new IOException("Could not parse error response.");
        } catch (JSONException e) {
            throw new IOException("Could not parse error response.");
        }
    } else if (statusCode != 200) {
        Log.e("Mustard", response.getStatusLine().getReasonPhrase());
        throw new MustardException(999, "Unmanaged response code: " + statusCode);
    }

    return response.getEntity().getContent();
}

From source file:org.mustard.util.HttpManager.java

private InputStream requestData(String url, ArrayList<NameValuePair> params, String attachmentParam,
        File attachment) throws IOException, MustardException, AuthException {

    URI uri;//w w  w.j  a v a2  s . co  m

    try {
        uri = new URI(url);
    } catch (URISyntaxException e) {
        throw new IOException("Invalid URL.");
    }
    if (MustardApplication.DEBUG)
        Log.d("HTTPManager", "Requesting " + uri);

    HttpPost post = new HttpPost(uri);

    HttpResponse response;

    // create the multipart request and add the parts to it 
    MultipartEntity requestContent = new MultipartEntity();
    long len = attachment.length();

    InputStream ins = new FileInputStream(attachment);
    InputStreamEntity ise = new InputStreamEntity(ins, -1L);
    byte[] data = EntityUtils.toByteArray(ise);

    String IMAGE_MIME = attachment.getName().toLowerCase().endsWith("png") ? IMAGE_MIME_PNG : IMAGE_MIME_JPG;
    requestContent.addPart(attachmentParam, new ByteArrayBody(data, IMAGE_MIME, attachment.getName()));

    if (params != null) {
        for (NameValuePair param : params) {
            len += param.getValue().getBytes().length;
            requestContent.addPart(param.getName(), new StringBody(param.getValue()));
        }
    }
    post.setEntity(requestContent);

    Log.d("Mustard", "Length: " + len);

    if (mHeaders != null) {
        Iterator<String> headKeys = mHeaders.keySet().iterator();
        while (headKeys.hasNext()) {
            String key = headKeys.next();
            post.setHeader(key, mHeaders.get(key));
        }
    }

    if (consumer != null) {
        try {
            consumer.sign(post);
        } catch (OAuthMessageSignerException e) {

        } catch (OAuthExpectationFailedException e) {

        } catch (OAuthCommunicationException e) {

        }
    }

    try {
        mClient.getParams().setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT,
                DEFAULT_POST_REQUEST_TIMEOUT);
        mClient.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT, DEFAULT_POST_REQUEST_TIMEOUT);
        response = mClient.execute(post);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        throw new IOException("HTTP protocol error.");
    }

    int statusCode = response.getStatusLine().getStatusCode();

    if (statusCode == 401) {
        throw new AuthException(401, "Unauthorized: " + url);
    } else if (statusCode == 403 || statusCode == 406) {
        try {
            JSONObject json = null;
            try {
                json = new JSONObject(StreamUtil.toString(response.getEntity().getContent()));
            } catch (JSONException e) {
                throw new MustardException(998, "Non json response: " + e.toString());
            }
            throw new MustardException(statusCode, json.getString("error"));
        } catch (IllegalStateException e) {
            throw new IOException("Could not parse error response.");
        } catch (JSONException e) {
            throw new IOException("Could not parse error response.");
        }
    } else if (statusCode != 200) {
        Log.e("Mustard", response.getStatusLine().getReasonPhrase());
        throw new MustardException(999, "Unmanaged response code: " + statusCode);
    }

    return response.getEntity().getContent();
}

From source file:com.game.simple.Game3.java

public static void uploadAvatar(final String token) {
    //---timer---//
    //StartReConnect();
    //-----------//
    self.runOnUiThread(new Runnable() {
        public void run() {
            if (cropedImagePath == null) {
                Toast.makeText(self.getApplicationContext(), "Cha chn nh !",
                        Toast.LENGTH_SHORT).show();
                return;
            }/*  w  ww  .  ja  v  a  2  s . c om*/
            if (cropedImagePath.compareTo(" ") == 0) {

                Toast.makeText(self.getApplicationContext(), "Cha chn nh !",
                        Toast.LENGTH_SHORT).show();
                return;
            } else {
                HttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPostRequest = new HttpPost(url);
                try {

                    File file = new File(cropedImagePath);
                    FileBody bin = new FileBody(file);
                    StringBody tok = new StringBody(token);
                    StringBody imageType = new StringBody("jpg");
                    MultipartEntityBuilder multiPartEntityBuilder = MultipartEntityBuilder.create();
                    multiPartEntityBuilder.addPart("token", tok);
                    multiPartEntityBuilder.addPart("imageType", imageType);
                    multiPartEntityBuilder.addPart("media", bin);
                    httpPostRequest.setEntity(multiPartEntityBuilder.build());

                    // Execute POST request to the given URL
                    HttpResponse httpResponse = null;
                    httpResponse = httpClient.execute(httpPostRequest);
                    // receive response as inputStream
                    InputStream inputStream = null;
                    inputStream = httpResponse.getEntity().getContent();

                    Log.e("--upload", "Upload complete");
                    Toast.makeText(self.getApplicationContext(), "Upload thnh cng!", Toast.LENGTH_SHORT)
                            .show();
                    String result = "";
                    if (inputStream != null)
                        result = convertInputStreamToString(inputStream);
                    else
                        result = " ";

                    Log.e("upload", result);
                    setlinkAvata(result);
                    cropedImagePath = " ";

                } catch (Exception e) {

                    Log.e("--Upload--", "ko the upload ");
                    Toast.makeText(self.getApplicationContext(),
                            "C li trong qu trnh upload!", Toast.LENGTH_SHORT).show();
                }
            } //else
        }
    });
    //---timer---//
    stopTimer();
    //-----------//
}

From source file:nl.sogeti.android.gpstracker.actions.ShareTrack.java

private void sendToJogmap(Uri fileUri, String contentType) {
    String authCode = PreferenceManager.getDefaultSharedPreferences(this).getString(Constants.JOGRUNNER_AUTH,
            "");/*  w w  w.  ja v  a2 s.  c o m*/
    File gpxFile = new File(fileUri.getEncodedPath());
    HttpClient httpclient = new DefaultHttpClient();
    HttpResponse response = null;
    URI jogmap = null;
    String jogmapResponseText = "";
    int statusCode = 0;
    try {
        jogmap = new URI(getString(R.string.jogmap_post_url));
        HttpPost method = new HttpPost(jogmap);

        MultipartEntity entity = new MultipartEntity();
        entity.addPart("id", new StringBody(authCode));
        entity.addPart("mFile", new FileBody(gpxFile));
        method.setEntity(entity);
        response = httpclient.execute(method);

        statusCode = response.getStatusLine().getStatusCode();
        InputStream stream = response.getEntity().getContent();
        jogmapResponseText = convertStreamToString(stream);
    } catch (IOException e) {
        Log.e(TAG, "Failed to upload to " + jogmap.toString(), e);
        CharSequence text = getString(R.string.jogmap_failed) + e.getLocalizedMessage();
        Toast toast = Toast.makeText(this, text, Toast.LENGTH_LONG);
        toast.show();
    } catch (URISyntaxException e) {
        //Log.e(TAG, "Failed to use configured URI " + jogmap.toString(), e);
        CharSequence text = getString(R.string.jogmap_failed) + e.getLocalizedMessage();
        Toast toast = Toast.makeText(this, text, Toast.LENGTH_LONG);
        toast.show();
    }
    if (statusCode == 200) {
        CharSequence text = getString(R.string.jogmap_success) + jogmapResponseText;
        Toast toast = Toast.makeText(this, text, Toast.LENGTH_LONG);
        toast.show();
    } else {
        Log.e(TAG, "Wrong status code " + statusCode);
        CharSequence text = getString(R.string.jogmap_failed) + jogmapResponseText;
        Toast toast = Toast.makeText(this, text, Toast.LENGTH_LONG);
        toast.show();
    }
}

From source file:cl.nic.dte.net.ConexionSii.java

private RECEPCIONDTEDocument uploadEnvio(String rutEnvia, String rutCompania, File archivoEnviarSII,
        String token, String urlEnvio, String hostEnvio)
        throws ClientProtocolException, IOException, org.apache.http.ParseException, XmlException {

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(urlEnvio);

    MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    reqEntity.addPart("rutSender", new StringBody(rutEnvia.substring(0, rutEnvia.length() - 2)));
    reqEntity.addPart("dvSender", new StringBody(rutEnvia.substring(rutEnvia.length() - 1, rutEnvia.length())));
    reqEntity.addPart("rutCompany", new StringBody(rutCompania.substring(0, (rutCompania).length() - 2)));
    reqEntity.addPart("dvCompany",
            new StringBody(rutCompania.substring(rutCompania.length() - 1, rutCompania.length())));

    FileBody bin = new FileBody(archivoEnviarSII);
    reqEntity.addPart("archivo", bin);

    httppost.setEntity(reqEntity);//from  w  w w . j a v  a 2  s.  c om

    BasicClientCookie cookie = new BasicClientCookie("TOKEN", token);
    cookie.setPath("/");
    cookie.setDomain(hostEnvio);
    cookie.setSecure(true);
    cookie.setVersion(1);

    CookieStore cookieStore = new BasicCookieStore();
    cookieStore.addCookie(cookie);

    httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);
    httppost.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY);

    HttpContext localContext = new BasicHttpContext();
    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

    httppost.addHeader(new BasicHeader("User-Agent", Utilities.netLabels.getString("UPLOAD_SII_HEADER_VALUE")));

    HttpResponse response = httpclient.execute(httppost, localContext);

    HttpEntity resEntity = response.getEntity();

    RECEPCIONDTEDocument resp = null;

    HashMap<String, String> namespaces = new HashMap<String, String>();
    namespaces.put("", "http://www.sii.cl/SiiDte");
    XmlOptions opts = new XmlOptions();
    opts.setLoadSubstituteNamespaces(namespaces);

    resp = RECEPCIONDTEDocument.Factory.parse(EntityUtils.toString(resEntity), opts);

    return resp;
}

From source file:com.ginstr.android.service.opencellid.upload.data.MeasurementsUploaderService.java

/**
 * Used to upload entries from networks table to OCID servers.
 *///from ww w.j  a  v a2 s  .  co m
private void uploadNetworks() {
    writeToLog("uploadNetworks()");

    String existingFileName = "uploadNetworks.csv";
    String data = null;

    NetworkDBIterator dbIterator = mDatabase.getNonUploadedNetworks();
    try {
        if (dbIterator.getCount() > 0) {
            //timestamp, mcc, mnc, net (network type), nen (network name)
            StringBuilder sb = new StringBuilder("timestamp,mcc,mnc,net,nen" + ((char) 0xA));

            while (dbIterator.hasNext() && uploadThreadRunning) {
                Network network = dbIterator.next();
                sb.append(network.getTimestamp()).append(",");
                sb.append(network.getMcc()).append(",");
                sb.append(network.getMnc()).append(",");
                sb.append(network.getType()).append(",");
                sb.append(network.getName());
                sb.append(((char) 0xA));
            }

            data = sb.toString();

        } else {
            writeToLog("No networks for upload.");
            return;
        }
    } finally {
        dbIterator.close();
    }

    writeToLog("uploadNetworks(): " + data);

    if (uploadThreadRunning) {

        try {
            httppost = new HttpPost(networksUrl);

            HttpResponse response = null;

            writeToLog("Upload request URL: " + httppost.getURI());

            if (uploadThreadRunning) {
                MultipartEntity mpEntity = new MultipartEntity();
                mpEntity.addPart("apikey", new StringBody(apiKey));
                mpEntity.addPart("datafile", new InputStreamBody(new ByteArrayInputStream(data.getBytes()),
                        "text/csv", existingFileName));

                ByteArrayOutputStream bArrOS = new ByteArrayOutputStream();
                // reqEntity is the MultipartEntity instance
                mpEntity.writeTo(bArrOS);
                bArrOS.flush();
                ByteArrayEntity bArrEntity = new ByteArrayEntity(bArrOS.toByteArray());
                bArrOS.close();

                bArrEntity.setChunked(false);
                bArrEntity.setContentEncoding(mpEntity.getContentEncoding());
                bArrEntity.setContentType(mpEntity.getContentType());

                httppost.setEntity(bArrEntity);

                response = httpclient.execute(httppost);
                if (response == null) {
                    writeToLog("Upload: null HTTP-response");
                    throw new IllegalStateException("no HTTP-response from server");
                }

                HttpEntity resEntity = response.getEntity();

                writeToLog("Response: " + response.getStatusLine().getStatusCode() + " - "
                        + response.getStatusLine());

                if (resEntity != null) {
                    writeToLog("Response content: " + EntityUtils.toString(resEntity));
                    resEntity.consumeContent();
                }
            }

            if (uploadThreadRunning) {
                if (response == null) {
                    writeToLog(": " + "null response");

                    throw new IllegalStateException("no response");
                }
                if (response.getStatusLine() == null) {
                    writeToLog(": " + "null HTTP-status-line");

                    throw new IllegalStateException("no HTTP-status returned");
                }
                if (response.getStatusLine().getStatusCode() == 200) {
                    mDatabase.setAllNetworksUploaded();
                } else if (response.getStatusLine().getStatusCode() != 200) {
                    throw new IllegalStateException(
                            response.getStatusLine().getStatusCode() + " HTTP-status returned");
                }
            }

        } catch (Exception e) {
            // httppost cancellation throws exceptions
            if (uploadThreadRunning) {
                writeExceptionToLog(e);
            }
        }
    }
}

From source file:com.groupon.odo.bmp.http.BrowserMobHttpRequest.java

public BrowserMobHttpResponse execute() {
    // deal with PUT/POST requests
    if (method instanceof HttpEntityEnclosingRequestBase) {
        HttpEntityEnclosingRequestBase enclodingRequest = (HttpEntityEnclosingRequestBase) method;

        if (!nvps.isEmpty()) {
            try {
                if (!multiPart) {
                    enclodingRequest.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
                } else {
                    for (NameValuePair nvp : nvps) {
                        multipartEntity.addPart(nvp.getName(), new StringBody(nvp.getValue()));
                    }//from   ww  w .java 2s .c o  m
                    enclodingRequest.setEntity(multipartEntity);
                }
            } catch (UnsupportedEncodingException e) {
                LOG.severe("Could not find UTF-8 encoding, something is really wrong", e);
            }
        } else if (multipartEntity != null) {
            enclodingRequest.setEntity(multipartEntity);
        } else if (byteArrayEntity != null) {
            enclodingRequest.setEntity(byteArrayEntity);
        } else if (stringEntity != null) {
            enclodingRequest.setEntity(stringEntity);
        } else if (inputStreamEntity != null) {
            enclodingRequest.setEntity(inputStreamEntity);
        }
    }

    return client.execute(this);
}

From source file:org.fcrepo.test.api.TestAdminAPI.java

private HttpResponse putOrPost(String method, Object requestContent, boolean authenticate) throws Exception {

    if (url == null || url.length() == 0) {
        throw new IllegalArgumentException("url must be a non-empty value");
    } else if (!(url.startsWith("http://") || url.startsWith("https://"))) {
        url = getBaseURL() + url;/*from   w  w w.  ja va2 s. c  o m*/
    }

    HttpEntityEnclosingRequestBase httpMethod = null;
    try {
        if (method.equals("PUT")) {
            httpMethod = new HttpPut(url);
        } else if (method.equals("POST")) {
            httpMethod = new HttpPost(url);
        } else {
            throw new IllegalArgumentException("method must be one of PUT or POST.");
        }
        httpMethod.setHeader(HttpHeaders.CONNECTION, "Keep-Alive");
        if (requestContent != null) {
            if (requestContent instanceof String) {
                StringEntity entity = new StringEntity((String) requestContent, Charset.forName("UTF-8"));
                entity.setChunked(chunked);
                httpMethod.setEntity(entity);
            } else if (requestContent instanceof File) {
                MultipartEntity entity = new MultipartEntity();
                entity.addPart(((File) requestContent).getName(), new FileBody((File) requestContent));
                entity.addPart("param_name", new StringBody("value"));
                httpMethod.setEntity(entity);
            } else {
                throw new IllegalArgumentException("requestContent must be a String or File");
            }
        }
        return getClient(authenticate).execute(httpMethod);
    } finally {
        if (httpMethod != null) {
            httpMethod.releaseConnection();
        }
    }
}