Example usage for org.apache.http.protocol HTTP UTF_8

List of usage examples for org.apache.http.protocol HTTP UTF_8

Introduction

In this page you can find the example usage for org.apache.http.protocol HTTP UTF_8.

Prototype

String UTF_8

To view the source code for org.apache.http.protocol HTTP UTF_8.

Click Source Link

Usage

From source file:org.ocsinventoryng.android.actions.OCSProtocol.java

public DefaultHttpClient getNewHttpClient(boolean strict) {
    try {//from   w w  w .j av  a  2s  .  c o m
        SSLSocketFactory sf;
        if (strict) {
            sf = SSLSocketFactory.getSocketFactory();
        } else {
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(null, null);
            sf = new CoolSSLSocketFactory(trustStore);
        }

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        HttpConnectionParams.setConnectionTimeout(params, 10000);
        HttpConnectionParams.setSoTimeout(params, 10000);

        return new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}

From source file:com.pagecrumb.proxy.ProxyServlet.java

@SuppressWarnings("unchecked")
protected void handleRequest(HttpServletRequest req, HttpServletResponse resp, boolean isPost)
        throws ServletException, IOException {

    log.info("contextPath=" + req.getContextPath());

    // Setup the headless browser
    WebClient webClient = new WebClient();

    webClient.setWebConnection(new UrlFetchWebConnection(webClient));

    HttpParams httpParams = new BasicHttpParams();
    httpParams.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000); // GAE constraint 

    // Originally, the design was to use HttpClient to execute methods
    // Now, it uses WebClient
    ClientConnectionManager connectionManager = new GAEConnectionManager();
    HttpClient httpclient = new DefaultHttpClient(connectionManager, httpParams);

    StringBuffer sb = new StringBuffer();

    log.info(getClass().toString() + " " + "URI Component=" + req.getRequestURI());
    log.info(getClass().toString() + " " + "URL Component=" + req.getRequestURL());

    if (req.getQueryString() != null) {
        //sb.append("?" + req.getQueryString());

        String s1 = Util.decodeURIComponent(req.getQueryString());
        log.info(getClass().toString() + " " + "QueryString=" + req.getQueryString());

        target = req.getQueryString();//from w  ww . j a  va  2  s .  c  o m
        int port = req.getServerPort();
        String domain = req.getServerName();

        URL url = new URL(SCHEME, domain, port, target);
        /*
        HtmlPage page = webClient.getPage(target);
                
        //gae hack because its single threaded
         webClient.getJavaScriptEngine().pumpEventLoop(PUMP_TIME);
                 
         pageString = page.asXml();
        */
    }

    sb.append(target);

    log.info(getClass().toString() + " " + "sb=" + sb.toString());

    HttpRequestBase targetRequest = null;

    if (isPost) {
        HttpPost post = new HttpPost(sb.toString());

        Enumeration<String> paramNames = req.getParameterNames();

        String paramName = null;

        List<NameValuePair> params = new ArrayList<NameValuePair>();

        while (paramNames.hasMoreElements()) {
            paramName = paramNames.nextElement();
            params.add(new BasicNameValuePair(paramName, req.getParameterValues(paramName)[0]));
        }

        post.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
        targetRequest = post;
    } else {
        HttpGet get = new HttpGet(sb.toString());
        targetRequest = get;
    }

    //        log.info("Request Headers");
    //        Enumeration<String> headerNames = req.getHeaderNames();
    //        String headerName = null;
    //        while(headerNames.hasMoreElements()){
    //            headerName = headerNames.nextElement();
    //            targetRequest.addHeader(headerName, req.getHeader(headerName));
    //            log.info(headerName + " : " + req.getHeader(headerName));
    //        }

    HttpResponse targetResponse = httpclient.execute(targetRequest);
    HttpEntity entity = targetResponse.getEntity();

    // Send the Response
    InputStream input = entity.getContent();
    OutputStream output = resp.getOutputStream();

    BufferedReader reader = new BufferedReader(new InputStreamReader(input));
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output));
    String line = reader.readLine();

    /*
     * To use the HttpClient instead the HtmlUnit's WebClient:
     */
    while (line != null) {
        writer.write(line + "\n");
        line = reader.readLine();
    }

    //        Scanner scanner = new Scanner(pageString);
    //        while (scanner.hasNextLine()) {
    //          String s = scanner.nextLine();
    //          writer.write(s + "\n");
    //        }
    if (webClient != null) {
        webClient.closeAllWindows();
    }

    reader.close();
    writer.close();

    httpclient.getConnectionManager().shutdown();
}

From source file:com.lostad.app.base.util.RequestUtil.java

public static String putForm(String url, List<NameValuePair> params, String token, boolean isSingleton)
        throws Exception {
    String json = null;//from ww  w .  jav  a 2  s  .  co  m
    HttpClient client = HttpClientManager.getHttpClient(isSingleton);
    HttpEntity resEntity = null;
    HttpPut put = new HttpPut(url);
    put.addHeader("token", token);
    try {
        put.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
        if (params != null) {
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
            if (params != null) {
                entity.setContentEncoding(HTTP.UTF_8);
                entity.setContentType("application/x-www-form-urlencoded");
            }
            put.setEntity(entity);
        }

        HttpResponse response = client.execute(put, new BasicHttpContext());
        resEntity = response.getEntity();
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {// 200
            // ?
            json = EntityUtils.toString(resEntity);
        }
    } catch (Exception e) {
        if (put != null) {
            put.abort();//
        }
        throw e;
    } finally {

        if (resEntity != null) {
            try {
                resEntity.consumeContent();//?

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        client.getConnectionManager().closeExpiredConnections();
        ///client.getConnectionManager().shutdown();
    }
    return json;

}

From source file:utils.XMSRestSender.java

public String POST(String dest, String xmlpayload) {
    //HttpResponse - After receiving and interpreting a request message, a server responds with an HTTP response message.
    //Response      = Status-Line
    //             *(( general-header
    //              | response-header
    //              | entity-header ) CRLF)
    //             CRLF
    //             [ message-body ]
    //http://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/HttpResponse.html?is-external=true
    HttpResponse response = null;//www. j  av  a  2  s.  c  o m

    //This string is used to store the XML extracted from the Response
    String xmlresponse = "";
    try {

        System.out.println("POST " + dest + "?appid=" + appid + "\n XMLPayload:\n" + xmlpayload);

        //HttpPost - HTTP POST method.
        // The HTTP POST method is defined in section 9.5 of RFC2616:
        // IN XMS REST Interface POST are used to create new Calls/Confs etc
        // http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/methods/HttpPost.html          

        // The POST requires an XML payload.  This block will convert the passed XML String to an http Entitiy and 
        // attach it to the post message.  Will also update the header to indicate the format of the payload is XML
        StringEntity se = new StringEntity(xmlpayload, HTTP.UTF_8);

        HttpPost httppost = new HttpPost(dest + "?appid=" + appid);
        httppost.setHeader("Content-Type", "text/xml;charset=UTF-8");
        httppost.setEntity(se);

        //Here you are issueing the POST Request, to the provided host via the HttpClient and storing
        //  the response in the HpptResponse
        response = httpclient.execute(host, httppost);

        //HttpEntity - An entity that can be sent or received with an HTTP message. 
        // Entities can be found in some requests and in responses, where they are optional.
        // http://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/HttpEntity.html
        HttpEntity entity = response.getEntity();

        //This block will dump out the Status, headers and message contents if available
        System.out.println(response.getStatusLine());
        Header[] headers = response.getAllHeaders();
        for (int i = 0; i < headers.length; i++) {
            System.out.println("   " + headers[i]);
        }
        System.out.println("****** Message Contents *******");

        if (entity != null) {
            xmlresponse = EntityUtils.toString(entity);
            System.out.println(xmlresponse);
        }
    } catch (IOException ex) {
        Logger.getLogger(XMSRestSender.class.getName()).log(Level.SEVERE, null, ex);
    }

    return xmlresponse;
}

From source file:vitro.vgw.communication.idas.IdasProxyImpl.java

private Object sendRequest(Object request) throws VitroGatewayException {

    Object result = null;/*  w  w  w  .j  a  v  a  2 s.c  o  m*/

    InputStream instream = null;

    try {
        HttpPost httpPost = new HttpPost(endPoint);

        JAXBContext jaxbContext = Utils.getJAXBContext();

        Marshaller mar = jaxbContext.createMarshaller();
        mar.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        mar.marshal(request, baos);

        String requestXML = baos.toString(HTTP.UTF_8);

        StringEntity entityPar = new StringEntity(requestXML, "application/xml", HTTP.UTF_8);

        httpPost.setEntity(entityPar);

        HttpResponse response = httpclient.execute(httpPost);
        HttpEntity entity = response.getEntity();
        if (entity != null) {

            instream = entity.getContent();

            Unmarshaller unmarshaller = Utils.getJAXBContext().createUnmarshaller();
            Object idasResponse = unmarshaller.unmarshal(instream);

            if (idasResponse instanceof ExceptionReport) {
                throw Utils.parseException((ExceptionReport) idasResponse);
            }

            result = idasResponse;

        } else {
            throw new VitroGatewayException("Server response does not contain any body");
        }
    } catch (VitroGatewayException e) {
        throw e;
    } catch (Exception e) {
        throw new VitroGatewayException(e);
    } finally {
        if (instream != null) {
            try {
                instream.close();
            } catch (IOException e) {
                logger.error("Error while closing server response stream", e);
            }
        }
    }

    return result;

}

From source file:org.craftercms.social.util.UGCHttpClient.java

public HttpResponse dislike(String ticket, String ugcId)
        throws URISyntaxException, ClientProtocolException, IOException {
    List<NameValuePair> qparams = new ArrayList<NameValuePair>();
    qparams.add(new BasicNameValuePair("ticket", ticket));
    URI uri = URIUtils.createURI(scheme, host, port, appPath + "/api/2/ugc/dislike/" + ugcId + ".json",
            URLEncodedUtils.format(qparams, HTTP.UTF_8), null);
    HttpPost httppost = new HttpPost(uri);
    HttpClient httpclient = new DefaultHttpClient();
    return httpclient.execute(httppost);
}

From source file:org.jlucrum.datafetcher.FetcherNasdaqOmxNordic.java

public Map<String, Double> getData(String name, DateTime fromDate, DateTime toDate, int type) {
    HttpPost httpPost = new HttpPost(this.url);
    HttpResponse response = null;//from  w  ww  .  ja  va  2s .c  om
    HashMap<String, Double> retMap = new HashMap<String, Double>();

    httpclient = getClient();

    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    String fixedName = stockMap.get(name);
    if (fixedName == null) {
        fixedName = name;
    }

    nameValuePairs.add(new BasicNameValuePair("xmlquery",
            "<post> " + "<param name=\"SubSystem\" value=\"History\"/> "
                    + "<param name=\"Action\" value=\"GetDataSeries\"/>"
                    + "<param name=\"AppendIntraDay\" value=\"no\"/>" + "<param name=\"Instrument\" value=\""
                    + fixedName + "\"/>" + "<param name=\"FromDate\" value=\"" + dateFormatter.print(fromDate)
                    + "\"/>" + "<param name=\"ToDate\" value=\"" + dateFormatter.print(toDate) + "\"/> "
                    + "<param name=\"hi__a\" value=\"0,1,2,4,21,8,10,11,12,9\"/> "
                    + "<param name=\"ext_xslt\" value=\"/nordicV3/hi_table_shares_adjusted.xsl\"/> "
                    + "<param name=\"ext_xslt_options\" value=\",undefined,\"/> "
                    + "<param name=\"ext_xslt_lang\" value=\"en\"/> "
                    + "<param name=\"ext_xslt_hiddenattrs\" value=\",ip,iv,\"/> "
                    + "<param name=\"ext_xslt_tableId\" value=\"historicalTable\"/> "
                    + "<param name=\"app\" value=\"/osakkeet/Historialliset_kurssitiedot/\"/> " + "</post>"));

    try {

        Document doc = (Document) cache.getData(fixedName, fromDate.toString(), toDate.toString());
        if (doc == null) {
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
            response = httpclient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            String resString = EntityUtils.toString(entity, "UTF-8");
            if (debug) {
                System.out.printf("Respond:%s", resString);
            }

            doc = Jsoup.parse(resString);
            cache.putData(fixedName, fromDate.toString(), toDate.toString(), doc);
            System.out.printf("Fetched from network:%s\n", name);
        }

        Elements elems = doc.select("tr");

        Iterator<Element> iter = elems.iterator();
        iter.next(); //skip head
        while (iter.hasNext()) {
            Element elem = iter.next();
            Elements dataElems = elem.getAllElements();
            /* Output Example:
            <tr id="historicalTable-">
              <td>2011-09-08</td>
              <td>25.29</td>
              <td>24.38</td>
              <td>24.93</td>
              <td>24.92</td>
              <td>895,389</td>
              <td>22,298,455</td>
              <td>5,524</td>
            </tr>
             */
            Element dateElem = dataElems.get(1);
            Element dataElem = dataElems.get(dataMap[type]);
            if (dateElem.html() == null || dateElem.html().length() == 0 || dataElem.html() == null
                    || dataElem.html().length() == 0) {
                continue;
            }

            retMap.put(dateElem.html(), Double.valueOf(dataElem.html().replaceAll(",", "")));

            if (debug) {
                System.out.printf("Date:%s data:%s\n", dateElem.html(), dataElem.html());
            }
        }

        System.out.printf("Fetched %s/%s from NasdaqOmxNordic:%d\n", name, fixedName, retMap.size());
    } catch (IOException ex) {
        Logger.getLogger(FetcherNasdaqOmxNordic.class.getName()).log(Level.SEVERE, null, ex);
    }

    return retMap;
}

From source file:com.lxh.util.image.OtherUtils.java

/**
 * ?HTTP?????/* w w w  . j  a  v  a  2 s  .com*/
 * @param response HTTP?{@link org.apache.http.HttpResponse}
 * @return ??
 */
public static String getFileNameFromHttpResponse(final HttpResponse response) {
    if (response == null)
        return null;
    String result = null;
    Header header = response.getFirstHeader("Content-Disposition");
    if (header != null) {
        for (HeaderElement element : header.getElements()) {
            NameValuePair fileNamePair = element.getParameterByName("filename");
            if (fileNamePair != null) {
                result = fileNamePair.getValue();
                // try to get correct encoding str
                result = CharsetUtils.toCharset(result, HTTP.UTF_8, result.length());
                break;
            }
        }
    }
    return result;
}

From source file:com.android.idtt.http.client.util.URIBuilder.java

private String encodeFragment(final String fragment) {
    return URLEncodedUtils.encFragment(fragment, Charset.forName(HTTP.UTF_8));
}

From source file:com.apigee.sdk.apm.http.impl.client.cache.URIExtractor.java

/**
 * For a given {@link HttpHost} and {@link HttpRequest} if the request has a
 * VARY header - I need to get an additional URI from the pair of host and
 * request so that I can also store the variant into my HttpCache.
 * /*  w w  w.  j  a  v a  2  s  . c  o m*/
 * @param host
 *            The host for this request
 * @param req
 *            the {@link HttpRequest}
 * @param entry
 *            the parent entry used to track the varients
 * @return String the extracted variant URI
 */
public String getVariantURI(HttpHost host, HttpRequest req, HttpCacheEntry entry) {
    Header[] varyHdrs = entry.getHeaders(HeaderConstants.VARY);
    if (varyHdrs == null || varyHdrs.length == 0) {
        return getURI(host, req);
    }

    List<String> variantHeaderNames = new ArrayList<String>();
    for (Header varyHdr : varyHdrs) {
        for (HeaderElement elt : varyHdr.getElements()) {
            variantHeaderNames.add(elt.getName());
        }
    }
    Collections.sort(variantHeaderNames);

    try {
        StringBuilder buf = new StringBuilder("{");
        boolean first = true;
        for (String headerName : variantHeaderNames) {
            if (!first) {
                buf.append("&");
            }
            buf.append(URLEncoder.encode(headerName, HTTP.UTF_8));
            buf.append("=");
            buf.append(URLEncoder.encode(getFullHeaderValue(req.getHeaders(headerName)), HTTP.UTF_8));
            first = false;
        }
        buf.append("}");
        buf.append(getURI(host, req));
        return buf.toString();
    } catch (UnsupportedEncodingException uee) {
        throw new RuntimeException("couldn't encode to UTF-8", uee);
    }
}