Example usage for org.apache.http.entity.mime MultipartEntity addPart

List of usage examples for org.apache.http.entity.mime MultipartEntity addPart

Introduction

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

Prototype

public void addPart(final String name, final ContentBody contentBody) 

Source Link

Usage

From source file:fm.smart.r1.activity.ItemActivity.java

public AddImageResult addImage(File file, String media_entity, String author, String author_url,
        String attribution_license_id, String sentence_id, String item_id, String list_id) {
    String http_response = "";
    int status_code = 0;
    HttpClient client = null;/*from   w  w  w  . j  a v  a2 s . c o m*/
    try {
        client = new DefaultHttpClient();
        HttpPost post = new HttpPost("http://api.smart.fm/lists/" + list_id + "/items/" + item_id
                + "/sentences/" + sentence_id + "/images");
        // HttpPost post = new HttpPost("http://api.smart.fm/sentences/" +
        // sentence_id
        // + "/images");

        String auth = Main.username(this) + ":" + Main.password(this);
        byte[] bytes = auth.getBytes();
        post.setHeader("Authorization", "Basic " + new String(Base64.encodeBase64(bytes)));

        // httppost.setHeader("Content-Type",
        // "application/x-www-form-urlencoded");

        post.setHeader("Host", "api.smart.fm");

        FileBody bin = new FileBody(file, "image/jpeg");
        StringBody media_entity_part = new StringBody(media_entity);
        StringBody author_part = new StringBody(author);
        StringBody author_url_part = new StringBody(author_url);
        StringBody attribution_license_id_part = new StringBody(attribution_license_id);
        StringBody sentence_id_part = new StringBody(sentence_id);
        StringBody api_key_part = new StringBody(Main.API_KEY);
        StringBody item_id_part = new StringBody(item_id);
        StringBody list_id_part = new StringBody(list_id);

        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart("image[file]", bin);
        reqEntity.addPart("media_entity", media_entity_part);
        reqEntity.addPart("author", author_part);
        reqEntity.addPart("author_url", author_url_part);
        reqEntity.addPart("attribution_license_id", attribution_license_id_part);
        reqEntity.addPart("sentence_id", sentence_id_part);
        reqEntity.addPart("api_key", api_key_part);
        reqEntity.addPart("item_id", item_id_part);
        reqEntity.addPart("list_id", list_id_part);

        post.setEntity(reqEntity);

        Header[] array = post.getAllHeaders();
        for (int i = 0; i < array.length; i++) {
            Log.d("DEBUG", array[i].toString());
        }

        Log.d("AddImage", "executing request " + post.getRequestLine());
        HttpResponse response = client.execute(post);
        HttpEntity resEntity = response.getEntity();
        status_code = response.getStatusLine().getStatusCode();

        Log.d("AddImage", "----------------------------------------");
        Log.d("AddImage", response.getStatusLine().toString());
        array = response.getAllHeaders();
        for (int i = 0; i < array.length; i++) {
            Log.d("AddImage", array[i].toString());
        }
        if (resEntity != null) {
            Log.d("AddImage", "Response content length: " + resEntity.getContentLength());
            Log.d("AddImage", "Chunked?: " + resEntity.isChunked());
        }
        long length = response.getEntity().getContentLength();
        byte[] response_bytes = new byte[(int) length];
        response.getEntity().getContent().read(response_bytes);
        Log.d("AddImage", new String(response_bytes));
        http_response = new String(response_bytes);
        if (resEntity != null) {
            resEntity.consumeContent();
        }

        // HttpEntity entity = response1.getEntity();
    } catch (IOException e) {
        /* Reset to Default image on any error. */
        e.printStackTrace();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return new AddImageResult(status_code, http_response);
}

From source file:net.zypr.api.Protocol.java

public JSONObject doStreamPost(APIVerbs apiVerb, Hashtable<String, String> urlParameters,
        Hashtable<String, String> postParameters, InputStream inputStream)
        throws APICommunicationException, APIProtocolException {
    if (!_apiEntity.equalsIgnoreCase("voice"))
        Session.getInstance().addActiveRequestCount();
    long t1 = System.currentTimeMillis();
    JSONObject jsonObject = null;/*from  ww w. j  av a  2  s  . c o  m*/
    JSONParser jsonParser = new JSONParser();
    try {
        DefaultHttpClient httpclient = getHTTPClient();
        HttpPost httpPost = new HttpPost(buildURL(apiVerb, urlParameters));
        HttpProtocolParams.setUseExpectContinue(httpPost.getParams(), false);
        MultipartEntity multipartEntity = new MultipartEntity();
        if (postParameters != null)
            for (Enumeration enumeration = postParameters.keys(); enumeration.hasMoreElements();) {
                String key = enumeration.nextElement().toString();
                String value = postParameters.get(key);
                multipartEntity.addPart(key, new StringBody(value));
                Debug.print("HTTP POST : " + key + "=" + value);
            }
        if (inputStream != null) {
            InputStreamBody inputStreamBody = new InputStreamBody(inputStream, "binary/octet-stream");
            multipartEntity.addPart("audio", inputStreamBody);
        }
        httpPost.setEntity(multipartEntity);
        HttpResponse httpResponse = httpclient.execute(httpPost);
        if (httpResponse.getStatusLine().getStatusCode() != 200)
            throw new APICommunicationException("HTTP Error " + httpResponse.getStatusLine().getStatusCode()
                    + " - " + httpResponse.getStatusLine().getReasonPhrase());
        HttpEntity httpEntity = httpResponse.getEntity();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpEntity.getContent()));
        jsonObject = (JSONObject) jsonParser.parse(bufferedReader);
        bufferedReader.close();
        httpclient.getConnectionManager().shutdown();
    } catch (ParseException parseException) {
        throw new APIProtocolException(parseException);
    } catch (IOException ioException) {
        throw new APICommunicationException(ioException);
    } catch (ClassCastException classCastException) {
        throw new APIProtocolException(classCastException);
    } finally {
        if (!_apiEntity.equalsIgnoreCase("voice"))
            Session.getInstance().removeActiveRequestCount();
        long t2 = System.currentTimeMillis();
        Debug.print(buildURL(apiVerb, urlParameters) + " : " + t1 + "-" + t2 + "=" + (t2 - t1) + " : "
                + jsonObject);
    }
    return (jsonObject);
}

From source file:net.dahanne.gallery3.client.business.G3Client.java

private HttpEntity requestToResponseEntity(String appendToGalleryUrl, List<NameValuePair> nameValuePairs,
        String requestMethod, File file)
        throws UnsupportedEncodingException, IOException, ClientProtocolException, G3GalleryException {
    HttpClient defaultHttpClient = new DefaultHttpClient();
    HttpRequestBase httpMethod;/*  www  .  j  av a2  s .  co  m*/
    //are we using rewritten urls ?
    if (this.isUsingRewrittenUrls && appendToGalleryUrl.contains(INDEX_PHP_REST)) {
        appendToGalleryUrl = StringUtils.remove(appendToGalleryUrl, "index.php");
    }

    logger.debug("requestToResponseEntity , url requested : {}", galleryItemUrl + appendToGalleryUrl);
    if (POST.equals(requestMethod)) {
        httpMethod = new HttpPost(galleryItemUrl + appendToGalleryUrl);
        httpMethod.setHeader(X_GALLERY_REQUEST_METHOD, requestMethod);
        if (file != null) {
            MultipartEntity multipartEntity = new MultipartEntity();

            String string = nameValuePairs.toString();
            // dirty fix to remove the enclosing entity{}
            String substring = string.substring(string.indexOf("{"), string.lastIndexOf("}") + 1);

            StringBody contentBody = new StringBody(substring, Charset.forName("UTF-8"));
            multipartEntity.addPart("entity", contentBody);
            FileBody fileBody = new FileBody(file);
            multipartEntity.addPart("file", fileBody);
            ((HttpPost) httpMethod).setEntity(multipartEntity);
        } else {
            ((HttpPost) httpMethod).setEntity(new UrlEncodedFormEntity(nameValuePairs));
        }
    } else if (PUT.equals(requestMethod)) {
        httpMethod = new HttpPost(galleryItemUrl + appendToGalleryUrl);
        httpMethod.setHeader(X_GALLERY_REQUEST_METHOD, requestMethod);
        ((HttpPost) httpMethod).setEntity(new UrlEncodedFormEntity(nameValuePairs));
    } else if (DELETE.equals(requestMethod)) {
        httpMethod = new HttpGet(galleryItemUrl + appendToGalleryUrl);
        httpMethod.setHeader(X_GALLERY_REQUEST_METHOD, requestMethod);
        //this is to avoid the HTTP 414 (length too long) error
        //it should only happen when getting items, index.php/rest/items?urls=
        //      } else if(appendToGalleryUrl.length()>2000) {
        //         String resource = appendToGalleryUrl.substring(0,appendToGalleryUrl.indexOf("?"));
        //         String variable = appendToGalleryUrl.substring(appendToGalleryUrl.indexOf("?")+1,appendToGalleryUrl.indexOf("="));
        //         String value = appendToGalleryUrl.substring(appendToGalleryUrl.indexOf("=")+1);
        //         httpMethod = new HttpPost(galleryItemUrl + resource);
        //         httpMethod.setHeader(X_GALLERY_REQUEST_METHOD, requestMethod);
        //         nameValuePairs.add(new BasicNameValuePair(variable, value));
        //         ((HttpPost) httpMethod).setEntity(new UrlEncodedFormEntity(
        //               nameValuePairs));
    } else {
        httpMethod = new HttpGet(galleryItemUrl + appendToGalleryUrl);
    }
    if (existingApiKey != null) {
        httpMethod.setHeader(X_GALLERY_REQUEST_KEY, existingApiKey);
    }
    //adding the userAgent to the request
    httpMethod.setHeader(USER_AGENT, userAgent);
    HttpResponse response = null;

    String[] patternsArray = new String[3];
    patternsArray[0] = "EEE, dd MMM-yyyy-HH:mm:ss z";
    patternsArray[1] = "EEE, dd MMM yyyy HH:mm:ss z";
    patternsArray[2] = "EEE, dd-MMM-yyyy HH:mm:ss z";
    try {
        // be extremely careful here, android httpclient needs it to be
        // an
        // array of string, not an arraylist
        defaultHttpClient.getParams().setParameter(CookieSpecPNames.DATE_PATTERNS, patternsArray);
        response = defaultHttpClient.execute(httpMethod);
    } catch (ClassCastException e) {
        List<String> patternsList = Arrays.asList(patternsArray);
        defaultHttpClient.getParams().setParameter(CookieSpecPNames.DATE_PATTERNS, patternsList);
        response = defaultHttpClient.execute(httpMethod);
    }

    int responseStatusCode = response.getStatusLine().getStatusCode();
    HttpEntity responseEntity = null;
    if (response.getEntity() != null) {
        responseEntity = response.getEntity();
    }

    switch (responseStatusCode) {
    case HttpURLConnection.HTTP_CREATED:
        break;
    case HttpURLConnection.HTTP_OK:
        break;
    case HttpURLConnection.HTTP_MOVED_TEMP:
        //the gallery is using rewritten urls, let's remember it and re hit the server
        this.isUsingRewrittenUrls = true;
        responseEntity = requestToResponseEntity(appendToGalleryUrl, nameValuePairs, requestMethod, file);
        break;
    case HttpURLConnection.HTTP_BAD_REQUEST:
        throw new G3BadRequestException();
    case HttpURLConnection.HTTP_FORBIDDEN:
        //for some reasons, the gallery may respond with 403 when trying to log in with the wrong url
        if (appendToGalleryUrl.contains(INDEX_PHP_REST)) {
            this.isUsingRewrittenUrls = true;
            responseEntity = requestToResponseEntity(appendToGalleryUrl, nameValuePairs, requestMethod, file);
            break;
        }
        throw new G3ForbiddenException();
    case HttpURLConnection.HTTP_NOT_FOUND:
        throw new G3ItemNotFoundException();
    default:
        throw new G3GalleryException("HTTP code " + responseStatusCode);
    }

    return responseEntity;
}

From source file:iqq.im.service.ApacheHttpService.java

@Override
public Future<QQHttpResponse> executeHttpRequest(QQHttpRequest request, QQHttpListener listener)
        throws QQException {
    try {/* w w  w  .ja v a 2  s.co m*/
        URI uri = URI.create(request.getUrl());

        if (request.getMethod().equals("POST")) {
            HttpPost httppost = new HttpPost(uri);
            HttpHost httphost = URIUtils.extractHost(uri);
            if (httphost == null) {
                LOG.error("host is null, url: " + uri.toString());
                httphost = new HttpHost(uri.getHost());
            }

            if (request.getReadTimeout() > 0) {
                HttpConnectionParams.setSoTimeout(httppost.getParams(), request.getReadTimeout());
            }
            if (request.getConnectTimeout() > 0) {
                HttpConnectionParams.setConnectionTimeout(httppost.getParams(), request.getConnectTimeout());
            }

            if (request.getFileMap().size() > 0) {
                MultipartEntity entity = new MultipartEntity();
                String charset = request.getCharset();

                Map<String, String> postMap = request.getPostMap();
                for (String key : postMap.keySet()) {
                    String value = postMap.get(key);
                    value = value == null ? "" : value;
                    entity.addPart(key, new StringBody(value, Charset.forName(charset)));
                }

                Map<String, File> fileMap = request.getFileMap();
                for (String key : fileMap.keySet()) {
                    File value = fileMap.get(key);
                    entity.addPart(new FormBodyPart(key, new FileBody(value, getMimeType(value))));
                }
                httppost.setEntity(entity);
            } else if (request.getPostMap().size() > 0) {
                List<NameValuePair> list = new ArrayList<NameValuePair>();

                Map<String, String> postMap = request.getPostMap();
                for (String key : postMap.keySet()) {
                    String value = postMap.get(key);
                    value = value == null ? "" : value;
                    list.add(new BasicNameValuePair(key, value));
                }
                httppost.setEntity(new UrlEncodedFormEntity(list, request.getCharset()));
            }
            Map<String, String> headerMap = request.getHeaderMap();
            for (String key : headerMap.keySet()) {
                httppost.addHeader(key, headerMap.get(key));
            }
            QQHttpPostRequestProducer producer = new QQHttpPostRequestProducer(httphost, httppost, listener);
            QQHttpResponseConsumer consumer = new QQHttpResponseConsumer(request, listener, cookieJar);
            QQHttpResponseCallback callback = new QQHttpResponseCallback(listener);
            Future<QQHttpResponse> future = asyncHttpClient.execute(producer, consumer, callback);
            return new ProxyFuture(future, consumer, producer);

        } else if (request.getMethod().equals("GET")) {
            HttpGet httpget = new HttpGet(uri);
            HttpHost httphost = URIUtils.extractHost(uri);
            if (httphost == null) {
                LOG.error("host is null, url: " + uri.toString());
                httphost = new HttpHost(uri.getHost());
            }
            Map<String, String> headerMap = request.getHeaderMap();
            for (String key : headerMap.keySet()) {
                httpget.addHeader(key, headerMap.get(key));
            }
            if (request.getReadTimeout() > 0) {
                HttpConnectionParams.setSoTimeout(httpget.getParams(), request.getReadTimeout());
            }
            if (request.getConnectTimeout() > 0) {
                HttpConnectionParams.setConnectionTimeout(httpget.getParams(), request.getConnectTimeout());
            }

            return asyncHttpClient.execute(new QQHttpGetRequestProducer(httphost, httpget),
                    new QQHttpResponseConsumer(request, listener, cookieJar),
                    new QQHttpResponseCallback(listener));

        } else {
            throw new QQException(QQErrorCode.IO_ERROR, "not support http method:" + request.getMethod());
        }
    } catch (IOException e) {
        throw new QQException(QQErrorCode.IO_ERROR);
    }
}

From source file:com.sytecso.jbpm.client.rs.JbpmRestTemplate.java

private String requestPost(String url, Map<String, Object> parameters, boolean multipart) throws Exception {
    log.info("--- POST");
    MultipartEntity multiPartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    List<BasicNameValuePair> formparams = new ArrayList<BasicNameValuePair>();
    if (parameters == null) {
        parameters = new HashMap<String, Object>();
    }/*from  w ww .  j  av a 2 s  .  c om*/
    Set<String> keys = parameters.keySet();
    for (String keyString : keys) {
        String value = parameters.get(keyString).toString();
        formparams.add(new BasicNameValuePair(keyString, value));
        if (multipart) {
            try {
                StringBody stringBody = new StringBody(value, Charset.forName("UTF-8"));
                //System.out.println(stringBody.);
                multiPartEntity.addPart(keyString, (ContentBody) stringBody);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
    HttpPost httpPost = new HttpPost(url);
    if (multipart) {
        httpPost.setEntity(multiPartEntity);
    } else {
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");// new UrlEncodedFormEntity(formparams, "multipart/form-data");
        ////
        httpPost.setEntity(entity);
    }
    /*if(!this.SESSION_ID.equals("")){
    httpPost.setHeader("Cookie", "JSESSIONID="+SESSION_ID); 
    }*/
    HttpResponse response = httpClient.execute(httpPost);
    return read(response.getEntity().getContent());
}

From source file:com.minws.frame.sdk.webqq.service.ApacheHttpService.java

/** {@inheritDoc} */
@Override/*from  ww  w.j a  v a2  s.c  om*/
public Future<QQHttpResponse> executeHttpRequest(QQHttpRequest request, QQHttpListener listener)
        throws QQException {
    try {
        URI uri = URI.create(request.getUrl());

        if (request.getMethod().equals("POST")) {
            HttpPost httppost = new HttpPost(uri);
            HttpHost httphost = URIUtils.extractHost(uri);
            if (httphost == null) {
                LOG.error("host is null, url: " + uri.toString());
                httphost = new HttpHost(uri.getHost());
            }

            if (request.getReadTimeout() > 0) {
                HttpConnectionParams.setSoTimeout(httppost.getParams(), request.getReadTimeout());
            }
            if (request.getConnectTimeout() > 0) {
                HttpConnectionParams.setConnectionTimeout(httppost.getParams(), request.getConnectTimeout());
            }

            if (request.getFileMap().size() > 0) {
                MultipartEntity entity = new MultipartEntity();
                String charset = request.getCharset();

                Map<String, String> postMap = request.getPostMap();
                for (String key : postMap.keySet()) {
                    String value = postMap.get(key);
                    value = value == null ? "" : value;
                    entity.addPart(key, new StringBody(value, Charset.forName(charset)));
                }

                Map<String, File> fileMap = request.getFileMap();
                for (String key : fileMap.keySet()) {
                    File value = fileMap.get(key);
                    entity.addPart(new FormBodyPart(key, new FileBody(value, getMimeType(value))));
                }
                httppost.setEntity(entity);
            } else if (request.getPostMap().size() > 0) {
                List<NameValuePair> list = new ArrayList<NameValuePair>();

                Map<String, String> postMap = request.getPostMap();
                for (String key : postMap.keySet()) {
                    String value = postMap.get(key);
                    value = value == null ? "" : value;
                    list.add(new BasicNameValuePair(key, value));
                }
                httppost.setEntity(new UrlEncodedFormEntity(list, request.getCharset()));
            }
            Map<String, String> headerMap = request.getHeaderMap();
            for (String key : headerMap.keySet()) {
                httppost.addHeader(key, headerMap.get(key));
            }
            QQHttpPostRequestProducer producer = new QQHttpPostRequestProducer(httphost, httppost, listener);
            QQHttpResponseConsumer consumer = new QQHttpResponseConsumer(request, listener, cookieJar);
            QQHttpResponseCallback callback = new QQHttpResponseCallback(listener);
            Future<QQHttpResponse> future = asyncHttpClient.execute(producer, consumer, callback);
            return new ProxyFuture(future, consumer, producer);

        } else if (request.getMethod().equals("GET")) {
            HttpGet httpget = new HttpGet(uri);
            HttpHost httphost = URIUtils.extractHost(uri);
            if (httphost == null) {
                LOG.error("host is null, url: " + uri.toString());
                httphost = new HttpHost(uri.getHost());
            }
            Map<String, String> headerMap = request.getHeaderMap();
            for (String key : headerMap.keySet()) {
                httpget.addHeader(key, headerMap.get(key));
            }
            if (request.getReadTimeout() > 0) {
                HttpConnectionParams.setSoTimeout(httpget.getParams(), request.getReadTimeout());
            }
            if (request.getConnectTimeout() > 0) {
                HttpConnectionParams.setConnectionTimeout(httpget.getParams(), request.getConnectTimeout());
            }

            return asyncHttpClient.execute(new QQHttpGetRequestProducer(httphost, httpget),
                    new QQHttpResponseConsumer(request, listener, cookieJar),
                    new QQHttpResponseCallback(listener));

        } else {
            throw new QQException(QQErrorCode.IO_ERROR, "not support http method:" + request.getMethod());
        }
    } catch (IOException e) {
        throw new QQException(QQErrorCode.IO_ERROR);
    }
}

From source file:com.marketplace.io.Sender.java

/**
 * Perform a complex HTTP Put (send files over the network)
 * //from  www.j  a v  a2 s. co  m
 * @param data
 *            file that needs to be sent
 * @param mimeType
 *            the content type of file
 * @param filename
 *            the name of file
 * @param url
 *            the location to send the file to
 * @throws ConnectivityException
 *             thrown if there was a problem connecting with the database
 */
public void doComplexHttpPut(byte[] data, String mimeType, String filename, String url)
        throws ConnectivityException {
    HttpResponse httpResponse = null;

    try {
        httpPut = new HttpPut();
        httpPut.setURI(new URI(url));
        httpPut.addHeader("content_type", "image/jpeg");
    } catch (URISyntaxException e) {
        throw new ConnectivityException("Error occured while setting URL");
    }

    ContentBody contentBody = new ByteArrayBody(data, mimeType, filename);

    MultipartEntity multipartEntity = new MultipartEntity();
    multipartEntity.addPart("image", contentBody);

    httpPut.setEntity(multipartEntity);

    try {
        httpResponse = httpClient.execute(httpPut);
        HttpEntity entity = httpResponse.getEntity();

        if (entity != null) {
            entity.getContent().close();
        }

    } catch (ClientProtocolException e) {
        throw new ConnectivityException("Error occured in Client Protocol");
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.marketplace.io.Sender.java

/**
 * Perform a complex HTTP Post (send files over the network)
 * /*from w  ww . jav a 2 s. c  o  m*/
 * @param data
 *            file that needs to be sent
 * @param mimeType
 *            the content type of file
 * @param filename
 *            the name of file
 * @param url
 *            the location to send the file to
 * @throws ConnectivityException
 *             thrown if there was a problem connecting with the database
 */
public void doComplexHttpPost(byte[] data, String mimeType, String filename, String url)
        throws ConnectivityException {
    HttpResponse httpResponse = null;

    try {
        httpPost = new HttpPost();
        httpPost.setURI(new URI(url));
        httpPost.addHeader("content_type", "image/jpeg");
    } catch (URISyntaxException e) {
        throw new ConnectivityException("Error occured while setting URL");
    }

    ContentBody contentBody = new ByteArrayBody(data, mimeType, filename);

    MultipartEntity multipartEntity = new MultipartEntity();
    multipartEntity.addPart("image", contentBody);

    httpPost.setEntity(multipartEntity);

    try {
        httpResponse = httpClient.execute(httpPost);
        HttpEntity entity = httpResponse.getEntity();

        if (entity != null) {
            entity.getContent().close();
        }

    } catch (ClientProtocolException e) {
        throw new ConnectivityException("Error occured in Client Protocol");
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.todoroo.astrid.actfm.sync.ActFmInvoker.java

public JSONObject postSync(String data, MultipartEntity entity, boolean changesHappened, String tok)
        throws IOException, ActFmServiceException {
    try {//  ww  w.  jav  a  2 s .  c o m
        String timeString = DateUtilities.timeToIso8601(DateUtilities.now(), true);

        Object[] params = { "token", tok, "data", data, "time", timeString };

        if (changesHappened) {
            String gcm = Preferences.getStringValue(GCMIntentService.PREF_REGISTRATION);
            ActFmSyncThread.syncLog("Sending GCM token: " + gcm);
            if (!TextUtils.isEmpty(gcm)) {
                params = AndroidUtilities.addToArray(Object.class, params, "gcm", gcm);
                entity.addPart("gcm", new StringBody(gcm));
            }
        }

        String request = createFetchUrl("api/" + API_VERSION, "synchronize", params);
        if (SYNC_DEBUG)
            Log.e("act-fm-post", request);
        Charset chars;
        try {
            chars = Charset.forName("UTF-8");
        } catch (Exception e) {
            chars = null;
        }

        entity.addPart("token", new StringBody(tok));
        entity.addPart("data", new StringBody(data, chars));
        entity.addPart("time", new StringBody(timeString));

        String response = restClient.post(request, entity);
        JSONObject object = new JSONObject(response);

        if (SYNC_DEBUG)
            AndroidUtilities.logJSONObject("act-fm-post-response", object);

        if (object.getString("status").equals("error"))
            throw new ActFmServiceException(object.getString("message"), object);
        return object;
    } catch (JSONException e) {
        throw new IOException(e.getMessage());
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.tellervo.desktop.wsi.WebJaxbAccessor.java

private INTYPE doRequest() throws IOException {
    HttpClient client = new ContentEncodingHttpClient();
    HttpUriRequest req;// www .j a  va 2s  .  c om
    JAXBContext context;
    Document outDocument = null;

    try {
        context = getJAXBContext();
    } catch (JAXBException jaxb) {
        throw new IOException("Unable to acquire JAXB context: " + jaxb.getMessage());
    }

    try {
        if (requestMethod == RequestMethod.POST) {
            if (this.sendingObject == null)
                throw new NullPointerException("requestDocument is null yet required for this type of query");

            // Create a new POST request
            HttpPost post = new HttpPost(url);
            // Make it a multipart post
            MultipartEntity postEntity = new MultipartEntity();
            req = post;

            // create an XML document from the given objects
            outDocument = marshallToDocument(context, sendingObject, getNamespacePrefixMapper());

            // add it to the http post request
            XMLBody xmlb = new XMLBody(outDocument, "application/tellervo+xml", null);
            postEntity.addPart("xmlrequest", xmlb);
            postEntity.addPart("traceback", new StringBody(getStackTrace()));
            post.setEntity(postEntity);
        } else {
            // well, that's nice and easy
            req = new HttpGet(url);
        }

        // debug this transaction...
        TransactionDebug.sent(outDocument, noun);

        // load cookies
        ((AbstractHttpClient) client).setCookieStore(WSCookieStoreHandler.getCookieStore().toCookieStore());

        req.setHeader("User-Agent", "Tellervo WSI " + Build.getUTF8Version() + " (" + clientModuleVersion
                + "; ts " + Build.getCompleteVersionNumber() + ")");

        if (App.prefs.getBooleanPref(PrefKey.WEBSERVICE_USE_STRICT_SECURITY, false)) {
            // Using strict security so don't allow self signed certificates for SSL
        } else {
            // Not using strict security so allow self signed certificates for SSL
            if (url.getScheme().equals("https"))
                WebJaxbAccessor.setSelfSignableHTTPSScheme(client);
        }

        // create a responsehandler
        JaxbResponseHandler<INTYPE> responseHandler = new JaxbResponseHandler<INTYPE>(context,
                receivingObjectClass);

        // set the schema we validate against
        responseHandler.setValidateSchema(getValidationSchema());

        // execute the actual http query
        INTYPE inObject = null;
        try {
            inObject = client.execute(req, responseHandler);
        } catch (EOFException e4) {
            log.debug("Caught EOFException");
        }

        TransactionDebug.received(inObject, noun, context);

        // save our cookies?
        WSCookieStoreHandler.getCookieStore().fromCookieStore(((AbstractHttpClient) client).getCookieStore());

        // ok, now inspect the document we got back
        //TellervoDocumentInspector inspector = new TellervoDocumentInspector(inDocument);

        // Verify our document based on schema validity
        //inspector.validate();

        // Verify our document structure, throw any exceptions!
        //inspector.verifyDocument();

        return inObject;
    } catch (UnknownHostException e) {
        throw new IOException("The URL of the server you have specified is unknown");
    }

    catch (HttpResponseException hre) {

        if (hre.getStatusCode() == 404) {
            throw new IOException("The URL of the server you have specified is unknown");
        }

        BugReport bugs = new BugReport(hre);

        bugs.addDocument("sent.xml", outDocument);

        new BugDialog(bugs);

        throw new IOException("The server returned a protocol error " + hre.getStatusCode() + ": "
                + hre.getLocalizedMessage());
    } catch (IllegalStateException ex) {
        throw new IOException("Webservice URL must be a full URL qualified with a communications protocol.\n"
                + "Tellervo currently supports http:// and https://.");
    }

    catch (ResponseProcessingException rspe) {
        Throwable cause = rspe.getCause();
        BugReport bugs = new BugReport(cause);
        Document invalidDoc = rspe.getNonvalidatingDocument();
        File invalidFile = rspe.getInvalidFile();

        if (outDocument != null)
            bugs.addDocument("sent.xml", outDocument);
        if (invalidDoc != null)
            bugs.addDocument("recv-nonvalid.xml", invalidDoc);
        if (invalidFile != null)
            bugs.addDocument("recv-malformed.xml", invalidFile);

        new BugDialog(bugs);

        XMLDebugView.addDocument(BugReport.getStackTrace(cause), "Parsing Exception", true);

        // it's probably an ioexception...
        if (cause instanceof IOException)
            throw (IOException) cause;

        throw rspe;
    } catch (XMLParsingException xmlpe) {
        Throwable cause = xmlpe.getCause();
        BugReport bugs = new BugReport(cause);
        Document invalidDoc = xmlpe.getNonvalidatingDocument();
        File invalidFile = xmlpe.getInvalidFile();

        bugs.addDocument("sent.xml", outDocument);
        if (invalidDoc != null)
            bugs.addDocument("recv-nonvalid.xml", invalidDoc);
        if (invalidFile != null)
            bugs.addDocument("recv-malformed.xml", invalidFile);

        new BugDialog(bugs);

        XMLDebugView.addDocument(BugReport.getStackTrace(cause), "Parsing Exception", true);

        // it's probably an ioexception...
        if (cause instanceof IOException)
            throw (IOException) cause;

        throw xmlpe;
    } catch (IOException ioe) {
        throw ioe;

    } catch (Exception uhe) {
        BugReport bugs = new BugReport(uhe);

        bugs.addDocument("sent.xml", outDocument);

        /*
        // MalformedDocs are handled automatically by BugReport class
        if(!(uhe instanceof MalformedDocumentException) && inDocument != null)
           bugs.addDocument("received.xml", inDocument);
        */

        new BugDialog(bugs);

        throw new IOException("Exception " + uhe.getClass().getName() + ": " + uhe.getLocalizedMessage());
    } finally {
        //?
    }
}