Example usage for org.apache.commons.httpclient.params HttpMethodParams HTTP_CONTENT_CHARSET

List of usage examples for org.apache.commons.httpclient.params HttpMethodParams HTTP_CONTENT_CHARSET

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.params HttpMethodParams HTTP_CONTENT_CHARSET.

Prototype

String HTTP_CONTENT_CHARSET

To view the source code for org.apache.commons.httpclient.params HttpMethodParams HTTP_CONTENT_CHARSET.

Click Source Link

Usage

From source file:com.momathink.common.tools.ToolMonitor.java

/**
 * HTTP POST?HTML/*  w ww  .j a  v  a 2s .c o  m*/
 *
 * @param url
 *            URL?
 * @param params
 *            ?,?null
 * @return ?HTML
 */
private String doPost(String url, Map<String, String> params) {
    StringBuffer result = new StringBuffer();
    HttpClient client = new HttpClient();
    PostMethod method = new PostMethod(url);
    method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
    // Http Post?
    if (params != null) {
        NameValuePair[] data = new NameValuePair[params.size()];
        int i = 0;
        for (Map.Entry<String, String> entry : params.entrySet()) {
            data[i++] = new NameValuePair(entry.getKey(), entry.getValue());
        }
        method.setRequestBody(data);
    }
    try {
        client.executeMethod(method);
        if (method.getStatusCode() == HttpStatus.SC_OK) {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(method.getResponseBodyAsStream(), "UTF-8"));
            String str = null;
            while ((str = reader.readLine()) != null) {
                result.append(str);
            }
        }
    } catch (IOException e) {
    } finally {
        method.releaseConnection();
    }
    return result.toString();
}

From source file:cn.vlabs.duckling.aone.client.impl.EmailAttachmentSenderImpl.java

/**
 * docIdemail// w  ww.ja  va  2  s .  com
 * 
 * @param fileName
 * @param email
 * @param teamId
 * @param docId
 * @param fileSize
 * @return
 */
private AttachmentPushResult createFileResouceInDDL(String email, int teamId, int docId,
        AttachmentInfo attachment) {
    AttachmentPushResult result = new AttachmentPushResult();
    setAttachResult(result, attachment);
    PostMethod method = new PostMethod(getDDLIp());
    method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
    method.addParameter(CLBID, docId + "");
    method.addParameter(EMAIL, email);
    method.addParameter(TEAMID, teamId + "");
    method.addParameter(FILESIZE, attachment.getFileSize() + "");
    method.addParameter(FILEID, attachment.getFileId());
    try {
        method.addParameter(FILENAME, URLEncoder.encode(attachment.getFileName(), "UTF-8"));
        int status = ddlClient.executeMethod(method);
        if (status >= 200 && status < 300) {
            String responseString = method.getResponseBodyAsString();
            AttachmentPushResult r = dealHttpResponse(responseString);
            setAttachResult(r, attachment);
            return r;
        } else {
            result.setStatusCode(AttachmentPushResult.NETWORK_ERROR);
            result.setMessage("DDL?" + status + "");
            return result;
        }
    } catch (HttpException e) {
        result.setStatusCode(AttachmentPushResult.NETWORK_ERROR);
        result.setMessage("DDL?" + e.getMessage() + "");
        return result;
    } catch (IOException e) {
        result.setStatusCode(AttachmentPushResult.IO_ERROR);
        result.setMessage("ddlIo");
        return result;
    } catch (Exception e) {
        result.setStatusCode(AttachmentPushResult.IO_ERROR);
        result.setMessage("ddl" + e.getStackTrace());
        return result;
    } finally {
        method.releaseConnection();
    }
}

From source file:com.openkm.extension.servlet.ZohoServlet.java

/**
 *   //from   w  w w .jav a2 s.  co  m
 */
private Map<String, String> sendToZoho(String zohoUrl, String nodeUuid, String lang)
        throws PathNotFoundException, AccessDeniedException, RepositoryException, DatabaseException,
        IOException, OKMException {
    Map<String, String> result = new HashMap<String, String>();
    File tmp = null;

    try {
        String path = OKMRepository.getInstance().getNodePath(null, nodeUuid);
        String fileName = PathUtils.getName(path);
        tmp = File.createTempFile("okm", ".tmp");
        InputStream is = OKMDocument.getInstance().getContent(null, path, false);
        Document doc = OKMDocument.getInstance().getProperties(null, path);
        FileOutputStream fos = new FileOutputStream(tmp);
        IOUtils.copy(is, fos);
        fos.flush();
        fos.close();

        String id = UUID.randomUUID().toString();
        String saveurl = Config.APPLICATION_BASE + "/extension/ZohoFileUpload";
        Part[] parts = { new FilePart("content", tmp), new StringPart("apikey", Config.ZOHO_API_KEY),
                new StringPart("output", "url"), new StringPart("mode", "normaledit"),
                new StringPart("filename", fileName), new StringPart("skey", Config.ZOHO_SECRET_KEY),
                new StringPart("lang", lang), new StringPart("id", id),
                new StringPart("format", getFormat(doc.getMimeType())), new StringPart("saveurl", saveurl) };

        PostMethod filePost = new PostMethod(zohoUrl);
        filePost.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
        filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams()));
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        int status = client.executeMethod(filePost);

        if (status == HttpStatus.SC_OK) {
            log.debug("OK: " + filePost.getResponseBodyAsString());
            ZohoToken zot = new ZohoToken();
            zot.setId(id);
            zot.setUser(getThreadLocalRequest().getRemoteUser());
            zot.setNode(nodeUuid);
            zot.setCreation(Calendar.getInstance());
            ZohoTokenDAO.create(zot);

            // Get the response
            BufferedReader rd = new BufferedReader(new InputStreamReader(filePost.getResponseBodyAsStream()));
            String line;

            while ((line = rd.readLine()) != null) {
                if (line.startsWith("URL=")) {
                    result.put("url", line.substring(4));
                    result.put("id", id);
                    break;
                }
            }

            rd.close();
        } else {
            String error = HttpStatus.getStatusText(status) + "\n\n" + filePost.getResponseBodyAsString();
            log.error("ERROR: {}", error);
            throw new OKMException(ErrorCode.get(ErrorCode.ORIGIN_OKMZohoService, ErrorCode.CAUSE_Zoho), error);
        }
    } finally {
        FileUtils.deleteQuietly(tmp);
    }

    return result;
}

From source file:net.duckling.ddl.service.resource.impl.ResourcePipeAgentServiceImpl.java

private JSONObject writeJson(JSONObject json) throws IOException {
    PostMethod method = new PostMethod(getQueryDomain() + "/pipe");
    method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
    Header h = new Header();
    h.setName("content-type");
    h.setValue("application/json");
    method.addRequestHeader(h);//  w ww  . java 2  s  .  co  m
    StringRequestEntity body = new StringRequestEntity(json.toString());
    method.setRequestEntity(body);
    try {
        int status = getHttpClient().executeMethod(method);
        if (status >= 200 && status < 300) {
            String result = getResponseBody(method.getResponseBodyAsStream());
            return new JSONObject(result);
        } else {
            return null;
        }
    } catch (HttpException e) {
        new IOException(e);
    } catch (IOException e) {
        throw e;
    } catch (ParseException e) {
        new IOException(e);
    } finally {
        method.releaseConnection();
    }
    return null;
}

From source file:net.duckling.ddl.service.resource.impl.ResourcePipeAgentServiceImpl.java

private String queryStatus(String taskId) throws IOException {
    GetMethod method = new GetMethod();
    method.setPath(getQueryDomain() + "/query?pipeTaskId=" + taskId);
    method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
    Header h = new Header();
    h.setName("content-type");
    h.setValue("application/json");
    method.addRequestHeader(h);//  w ww  .  jav a  2 s  .com
    try {
        int status = getHttpClient().executeMethod(method);
        if (status >= 200 && status < 300) {
            return getResponseBody(method.getResponseBodyAsStream());
        } else {
            return "";
        }
    } catch (HttpException e) {
        new IOException(e);
    } catch (IOException e) {
        throw e;
    } finally {
        method.releaseConnection();
    }
    return "";
}

From source file:com.kaltura.client.KalturaClientBase.java

protected HttpClient createHttpClient() {
    HttpClient client = new HttpClient();

    // added by Unicon to handle proxy hosts
    String proxyHost = System.getProperty("http.proxyHost");
    if (proxyHost != null) {
        int proxyPort = -1;
        String proxyPortStr = System.getProperty("http.proxyPort");
        if (proxyPortStr != null) {
            try {
                proxyPort = Integer.parseInt(proxyPortStr);
            } catch (NumberFormatException e) {
                if (logger.isEnabled())
                    logger.warn("Invalid number for system property http.proxyPort (" + proxyPortStr
                            + "), using default port instead");
            }/*  w  w  w  .  j ava2s . c  om*/
        }
        ProxyHost proxy = new ProxyHost(proxyHost, proxyPort);
        client.getHostConfiguration().setProxyHost(proxy);
    }
    // added by Unicon to force encoding to UTF-8
    client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, UTF8_CHARSET);
    client.getParams().setParameter(HttpMethodParams.HTTP_ELEMENT_CHARSET, UTF8_CHARSET);
    client.getParams().setParameter(HttpMethodParams.HTTP_URI_CHARSET, UTF8_CHARSET);

    HttpConnectionManagerParams connParams = client.getHttpConnectionManager().getParams();
    if (this.kalturaConfiguration.getTimeout() != 0) {
        connParams.setSoTimeout(this.kalturaConfiguration.getTimeout());
        connParams.setConnectionTimeout(this.kalturaConfiguration.getTimeout());
    }
    client.getHttpConnectionManager().setParams(connParams);
    return client;
}

From source file:com.borhan.client.BorhanClientBase.java

protected HttpClient createHttpClient() {
    HttpClient client = new HttpClient();

    // added by Unicon to handle proxy hosts
    String proxyHost = System.getProperty("http.proxyHost");
    if (proxyHost != null) {
        int proxyPort = -1;
        String proxyPortStr = System.getProperty("http.proxyPort");
        if (proxyPortStr != null) {
            try {
                proxyPort = Integer.parseInt(proxyPortStr);
            } catch (NumberFormatException e) {
                if (logger.isEnabled())
                    logger.warn("Invalid number for system property http.proxyPort (" + proxyPortStr
                            + "), using default port instead");
            }//from  w w  w.j a  v a2s  .c o  m
        }
        ProxyHost proxy = new ProxyHost(proxyHost, proxyPort);
        client.getHostConfiguration().setProxyHost(proxy);
    }
    // added by Unicon to force encoding to UTF-8
    client.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, UTF8_CHARSET);
    client.getParams().setParameter(HttpMethodParams.HTTP_ELEMENT_CHARSET, UTF8_CHARSET);
    client.getParams().setParameter(HttpMethodParams.HTTP_URI_CHARSET, UTF8_CHARSET);

    HttpConnectionManagerParams connParams = client.getHttpConnectionManager().getParams();
    if (this.borhanConfiguration.getTimeout() != 0) {
        connParams.setSoTimeout(this.borhanConfiguration.getTimeout());
        connParams.setConnectionTimeout(this.borhanConfiguration.getTimeout());
    }
    client.getHttpConnectionManager().setParams(connParams);
    return client;
}

From source file:net.duckling.ddl.web.controller.AttachmentController.java

public static String getClbToken(int docId, int version, Properties properties) {
    HttpClient client = getHttpClient();
    PostMethod method = new PostMethod(getClbTokenUrl(properties));
    method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
    method.addParameter("appname", properties.getProperty("duckling.clb.aone.user"));
    method.addParameter("docid", docId + "");
    method.addParameter("version", version + "");
    try {/* w w  w .  j  a  v  a  2 s  . c  om*/
        method.addParameter("password",
                Base64.encodeBytes(properties.getProperty("duckling.clb.aone.password").getBytes("utf-8")));
    } catch (IllegalArgumentException | UnsupportedEncodingException e) {

    }
    try {
        int status = client.executeMethod(method);
        String responseString = null;
        if (status < 400) {
            responseString = method.getResponseBodyAsString();
            org.json.JSONObject j = new org.json.JSONObject(responseString);
            Object st = j.get("status");
            if ("failed".equals(st)) {
                LOG.error("?clb token?");
                return null;
            } else {
                return j.get("pf").toString();
            }
        } else {
            LOG.error("STAUTS:" + status + ";MESSAGE:" + responseString);
        }
    } catch (HttpException e) {
        LOG.error("", e);
    } catch (IOException e) {
        LOG.error("", e);
    } catch (ParseException e) {
        LOG.error("", e);
    }
    return null;
}

From source file:com.twelve.capital.external.feed.util.HttpImpl.java

protected byte[] URLtoByteArray(String location, Http.Method method, Map<String, String> headers,
        Cookie[] cookies, Http.Auth auth, Http.Body body, List<Http.FilePart> fileParts,
        Map<String, String> parts, Http.Response response, boolean followRedirects, String progressId,
        PortletRequest portletRequest) throws IOException {

    byte[] bytes = null;

    HttpMethod httpMethod = null;//from  w  w  w.  j  a va  2s .co m
    HttpState httpState = null;

    try {
        _cookies.set(null);

        if (location == null) {
            return null;
        } else if (!location.startsWith(Http.HTTP_WITH_SLASH) && !location.startsWith(Http.HTTPS_WITH_SLASH)) {

            location = Http.HTTP_WITH_SLASH + location;
        }

        HostConfiguration hostConfiguration = getHostConfiguration(location);

        HttpClient httpClient = getClient(hostConfiguration);

        if (method.equals(Http.Method.POST) || method.equals(Http.Method.PUT)) {

            if (method.equals(Http.Method.POST)) {
                httpMethod = new PostMethod(location);
            } else {
                httpMethod = new PutMethod(location);
            }

            if (body != null) {
                RequestEntity requestEntity = new StringRequestEntity(body.getContent(), body.getContentType(),
                        body.getCharset());

                EntityEnclosingMethod entityEnclosingMethod = (EntityEnclosingMethod) httpMethod;

                entityEnclosingMethod.setRequestEntity(requestEntity);
            } else if (method.equals(Http.Method.POST)) {
                PostMethod postMethod = (PostMethod) httpMethod;

                if (!hasRequestHeader(postMethod, HttpHeaders.CONTENT_TYPE)) {

                    HttpClientParams httpClientParams = httpClient.getParams();

                    httpClientParams.setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, StringPool.UTF8);
                }

                processPostMethod(postMethod, fileParts, parts);
            }
        } else if (method.equals(Http.Method.DELETE)) {
            httpMethod = new DeleteMethod(location);
        } else if (method.equals(Http.Method.HEAD)) {
            httpMethod = new HeadMethod(location);
        } else {
            httpMethod = new GetMethod(location);
        }

        if (headers != null) {
            for (Map.Entry<String, String> header : headers.entrySet()) {
                httpMethod.addRequestHeader(header.getKey(), header.getValue());
            }
        }

        if ((method.equals(Http.Method.POST) || method.equals(Http.Method.PUT)) && ((body != null)
                || ((fileParts != null) && !fileParts.isEmpty()) || ((parts != null) && !parts.isEmpty()))) {
        } else if (!hasRequestHeader(httpMethod, HttpHeaders.CONTENT_TYPE)) {
            httpMethod.addRequestHeader(HttpHeaders.CONTENT_TYPE,
                    ContentTypes.APPLICATION_X_WWW_FORM_URLENCODED_UTF8);
        }

        if (!hasRequestHeader(httpMethod, HttpHeaders.USER_AGENT)) {
            httpMethod.addRequestHeader(HttpHeaders.USER_AGENT, _DEFAULT_USER_AGENT);
        }

        httpState = new HttpState();

        if (ArrayUtil.isNotEmpty(cookies)) {
            org.apache.commons.httpclient.Cookie[] commonsCookies = toCommonsCookies(cookies);

            httpState.addCookies(commonsCookies);

            HttpMethodParams httpMethodParams = httpMethod.getParams();

            httpMethodParams.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
        }

        if (auth != null) {
            httpMethod.setDoAuthentication(true);

            httpState.setCredentials(new AuthScope(auth.getHost(), auth.getPort(), auth.getRealm()),
                    new UsernamePasswordCredentials(auth.getUsername(), auth.getPassword()));
        }

        proxifyState(httpState, hostConfiguration);

        int responseCode = httpClient.executeMethod(hostConfiguration, httpMethod, httpState);

        response.setResponseCode(responseCode);

        Header locationHeader = httpMethod.getResponseHeader("location");

        if ((locationHeader != null) && !locationHeader.equals(location)) {
            String redirect = locationHeader.getValue();

            if (followRedirects) {
                return URLtoByteArray(redirect, Http.Method.GET, headers, cookies, auth, body, fileParts, parts,
                        response, followRedirects, progressId, portletRequest);
            } else {
                response.setRedirect(redirect);
            }
        }

        InputStream inputStream = httpMethod.getResponseBodyAsStream();

        if (inputStream != null) {
            int contentLength = 0;

            Header contentLengthHeader = httpMethod.getResponseHeader(HttpHeaders.CONTENT_LENGTH);

            if (contentLengthHeader != null) {
                contentLength = GetterUtil.getInteger(contentLengthHeader.getValue());

                response.setContentLength(contentLength);
            }

            Header contentType = httpMethod.getResponseHeader(HttpHeaders.CONTENT_TYPE);

            if (contentType != null) {
                response.setContentType(contentType.getValue());
            }

            if (Validator.isNotNull(progressId) && (portletRequest != null)) {

                ProgressInputStream progressInputStream = new ProgressInputStream(portletRequest, inputStream,
                        contentLength, progressId);

                UnsyncByteArrayOutputStream unsyncByteArrayOutputStream = new UnsyncByteArrayOutputStream(
                        contentLength);

                try {
                    progressInputStream.readAll(unsyncByteArrayOutputStream);
                } finally {
                    progressInputStream.clearProgress();
                }

                bytes = unsyncByteArrayOutputStream.unsafeGetByteArray();

                unsyncByteArrayOutputStream.close();
            } else {
                bytes = FileUtil.getBytes(inputStream);
            }
        }

        for (Header header : httpMethod.getResponseHeaders()) {
            response.addHeader(header.getName(), header.getValue());
        }

        return bytes;
    } finally {
        try {
            if (httpState != null) {
                _cookies.set(toServletCookies(httpState.getCookies()));
            }
        } catch (Exception e) {
            _log.error(e, e);
        }

        try {
            if (httpMethod != null) {
                httpMethod.releaseConnection();
            }
        } catch (Exception e) {
            _log.error(e, e);
        }
    }
}

From source file:net.neurowork.cenatic.centraldir.workers.XMLRestWorker.java

public static HttpClient getHttpClient() {
    HttpClient httpclient = new HttpClient();
    //      httpclient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, HTTP_CONTEXT_CHARSET_ISO_8859_1);
    httpclient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, HTTP_CONTEXT_CHARSET_UTF_8);

    return httpclient;
}