Example usage for org.apache.http.util EntityUtils toString

List of usage examples for org.apache.http.util EntityUtils toString

Introduction

In this page you can find the example usage for org.apache.http.util EntityUtils toString.

Prototype

public static String toString(HttpEntity httpEntity) throws IOException, ParseException 

Source Link

Usage

From source file:com.niceapps.app.HttpClient.java

public static JSONObject SendHttpPost(String URL, JSONObject jsonObjSend) {

    try {// ww w . j a v a  2 s.  c om
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpPost httpPostRequest = new HttpPost(URL);

        StringEntity se;
        se = new StringEntity(jsonObjSend.toString());

        // Set HTTP parameters
        httpPostRequest.setEntity(se);
        httpPostRequest.setHeader("Accept", "application/json");
        httpPostRequest.setHeader("Content-Type", "application/json");

        HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);

        if (response.getStatusLine().getStatusCode() == 200) {
            HttpEntity entity = response.getEntity();
            JSONObject jsonObjRecv = new JSONObject(EntityUtils.toString(entity));

            return jsonObjRecv;
        } else {
            return null;
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:ru.apertum.qsystem.reports.net.NetUtil.java

public static synchronized String getEntityContent(HttpRequest request) {
    String result = map_ec.get(request);
    if (result == null) {

        if (request instanceof HttpEntityEnclosingRequest) {
            HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
            try {
                result = EntityUtils.toString(entity);
            } catch (IOException | ParseException ex) {
                throw new ReportException(ex.toString());
            }//from   ww w  . jav a  2 s.co  m
        } else {
            result = "";
        }
        try {
            result = URLDecoder.decode(result, "utf-8");
        } catch (UnsupportedEncodingException ex) {
            throw new ReportException(ex.toString());
        }
        map_ec.put(request, result);
    }
    return result;
}

From source file:org.blanco.techmun.android.misc.XmlParser.java

public static synchronized Document parseHttpEntity(HttpEntity entity) throws Exception {
    Document doc = null;// w w w.  ja va 2 s  .  c o  m
    String xmlString = null;
    try {
        xmlString = EntityUtils.toString(entity);
        DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        doc = docBuilder.parse(new InputSource(new StringReader(xmlString)));
        return doc;
    } catch (ParseException e1) {
        throw new Exception("Error parsing the entity.", e1);
    } catch (IOException e1) {
        throw new Exception("Error while reading the entity.", e1);
    } catch (ParserConfigurationException e) {
        throw new Exception("Error in the parser configuration.", e);
    } catch (SAXException e) {
        throw new Exception("Error parsing the entity.", e);
    }
}

From source file:org.openinfinity.cloud.util.http.HttpHelper.java

public static String executeHttpRequest(HttpClient client, String url) {
    HttpUriRequest request = new HttpGet(url);

    try {// ww  w.j  av  a2  s  .  c om
        HttpResponse response = client.execute(request);
        int status = response.getStatusLine().getStatusCode();
        if (status >= 200 && status < 300) {
            HttpEntity entity = response.getEntity();
            return entity != null ? EntityUtils.toString(entity) : null;
        }
    } catch (ClientProtocolException e) {
        LOG.warn(EXCEPTION_WHILE_EXECUTING_HTTP_REQUEST + "----" + e.getMessage());
    } catch (IOException e) {
        LOG.warn(EXCEPTION_WHILE_EXECUTING_HTTP_REQUEST + "----" + e.getMessage());
    } catch (Exception e) {
        LOG.warn(EXCEPTION_WHILE_EXECUTING_HTTP_REQUEST + "----" + e.getMessage());
    }
    return null;
}

From source file:com.li.tools.httpclient.util.ClientConfiguration.java

public final static void main(String[] args) throws Exception {

    // Use custom message parser / writer to customize the way HTTP
    // messages are parsed from and written out to the data stream.
    HttpMessageParserFactory<HttpResponse> responseParserFactory = new DefaultHttpResponseParserFactory() {

        @Override/*from   ww  w .  j  a  v a  2  s .c  o  m*/
        public HttpMessageParser<HttpResponse> create(SessionInputBuffer buffer,
                MessageConstraints constraints) {
            LineParser lineParser = new BasicLineParser() {

                @Override
                public Header parseHeader(final CharArrayBuffer buffer) {
                    try {
                        return super.parseHeader(buffer);
                    } catch (ParseException ex) {
                        return new BasicHeader(buffer.toString(), null);
                    }
                }

            };
            return new DefaultHttpResponseParser(buffer, lineParser, DefaultHttpResponseFactory.INSTANCE,
                    constraints) {

                @Override
                protected boolean reject(final CharArrayBuffer line, int count) {
                    // try to ignore all garbage preceding a status line infinitely
                    return false;
                }

            };
        }

    };
    HttpMessageWriterFactory<HttpRequest> requestWriterFactory = new DefaultHttpRequestWriterFactory();

    // Use a custom connection factory to customize the process of
    // initialization of outgoing HTTP connections. Beside standard connection
    // configuration parameters HTTP connection factory can define message
    // parser / writer routines to be employed by individual connections.
    HttpConnectionFactory<HttpRoute, ManagedHttpClientConnection> connFactory = new ManagedHttpClientConnectionFactory(
            requestWriterFactory, responseParserFactory);

    // Client HTTP connection objects when fully initialized can be bound to
    // an arbitrary network socket. The process of network socket initialization,
    // its connection to a remote address and binding to a local one is controlled
    // by a connection socket factory.

    // SSL context for secure connections can be created either based on
    // system or application specific properties.
    SSLContext sslcontext = SSLContexts.createSystemDefault();

    // Create a registry of custom connection socket factories for supported
    // protocol schemes.
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.INSTANCE)
            .register("https", new SSLConnectionSocketFactory(sslcontext)).build();

    // Use custom DNS resolver to override the system DNS resolution.
    DnsResolver dnsResolver = new SystemDefaultDnsResolver() {

        @Override
        public InetAddress[] resolve(final String host) throws UnknownHostException {
            if (host.equalsIgnoreCase("myhost")) {
                return new InetAddress[] { InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 }) };
            } else {
                return super.resolve(host);
            }
        }

    };

    // Create a connection manager with custom configuration.
    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(
            socketFactoryRegistry, connFactory, dnsResolver);

    // Create socket configuration
    SocketConfig socketConfig = SocketConfig.custom().setTcpNoDelay(true).build();
    // Configure the connection manager to use socket configuration either
    // by default or for a specific host.
    connManager.setDefaultSocketConfig(socketConfig);
    connManager.setSocketConfig(new HttpHost("somehost", 80), socketConfig);
    // Validate connections after 1 sec of inactivity
    connManager.setValidateAfterInactivity(1000);

    // Create message constraints
    MessageConstraints messageConstraints = MessageConstraints.custom().setMaxHeaderCount(200)
            .setMaxLineLength(2000).build();
    // Create connection configuration
    ConnectionConfig connectionConfig = ConnectionConfig.custom()
            .setMalformedInputAction(CodingErrorAction.IGNORE)
            .setUnmappableInputAction(CodingErrorAction.IGNORE).setCharset(Consts.UTF_8)
            .setMessageConstraints(messageConstraints).build();
    // Configure the connection manager to use connection configuration either
    // by default or for a specific host.
    connManager.setDefaultConnectionConfig(connectionConfig);
    connManager.setConnectionConfig(new HttpHost("somehost", 80), ConnectionConfig.DEFAULT);

    // Configure total max or per route limits for persistent connections
    // that can be kept in the pool or leased by the connection manager.
    connManager.setMaxTotal(100);
    connManager.setDefaultMaxPerRoute(10);
    connManager.setMaxPerRoute(new HttpRoute(new HttpHost("somehost", 80)), 20);

    // Use custom cookie store if necessary.
    CookieStore cookieStore = new BasicCookieStore();
    // Use custom credentials provider if necessary.
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    // Create global request configuration
    RequestConfig defaultRequestConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.DEFAULT)
            .setExpectContinueEnabled(true)
            .setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST))
            .setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).build();

    // Create an HttpClient with the given custom dependencies and configuration.
    CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(connManager)
            .setDefaultCookieStore(cookieStore).setDefaultCredentialsProvider(credentialsProvider)
            .setProxy(new HttpHost("myproxy", 8080)).setDefaultRequestConfig(defaultRequestConfig).build();

    try {
        HttpGet httpget = new HttpGet("http://httpbin.org/get");
        // Request configuration can be overridden at the request level.
        // They will take precedence over the one set at the client level.
        RequestConfig requestConfig = RequestConfig.copy(defaultRequestConfig).setSocketTimeout(5000)
                .setConnectTimeout(5000).setConnectionRequestTimeout(5000)
                .setProxy(new HttpHost("myotherproxy", 8080)).build();
        httpget.setConfig(requestConfig);

        // Execution context can be customized locally.
        HttpClientContext context = HttpClientContext.create();
        // Contextual attributes set the local context level will take
        // precedence over those set at the client level.
        context.setCookieStore(cookieStore);
        context.setCredentialsProvider(credentialsProvider);

        System.out.println("executing request " + httpget.getURI());
        CloseableHttpResponse response = httpclient.execute(httpget, context);
        try {
            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());
            System.out.println(EntityUtils.toString(response.getEntity()));
            System.out.println("----------------------------------------");

            // Once the request has been executed the local context can
            // be used to examine updated state and various objects affected
            // by the request execution.

            // Last executed request
            context.getRequest();
            // Execution route
            context.getHttpRoute();
            // Target auth state
            context.getTargetAuthState();
            // Proxy auth state
            context.getTargetAuthState();
            // Cookie origin
            context.getCookieOrigin();
            // Cookie spec used
            context.getCookieSpec();
            // User security token
            context.getUserToken();

        } finally {
            response.close();
        }
    } finally {
        httpclient.close();
    }
}

From source file:me.xingrz.prox.pac.AutoConfig.java

/**
 *  {@code url} ? PAC //www.jav a  2 s.c  om
 *
 * @param url PAC ?
 * @return  {@code ProxAutoConfig} 
 * @throws IOException
 */
public static AutoConfig fromUrl(String url) throws IOException {
    HttpResponse response = new DefaultHttpClient().execute(new HttpGet(url));
    String config = EntityUtils.toString(response.getEntity());
    return new AutoConfig(config);
}

From source file:com.alta189.cyborg.commandkit.util.HttpUtil.java

public static String readURL(String url) {
    HttpGet request = new HttpGet(url);
    HttpClient httpClient = new DefaultHttpClient();
    try {//from w  ww.  jav  a2s . c o m
        HttpResponse response = httpClient.execute(request);
        return EntityUtils.toString(response.getEntity());
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.outburstframework.test.util.http.HTTPUtils.java

/**
 * Makes a HTTP Get request./*from w w w. j ava 2  s .c om*/
 * 
 * @param url
  *          The URL fo the page you would like to return
 * @return The body of the HTTP request
 * @throws HTTPException
  *              The was a problem making the request
 * @throws InvalidResponseException
 *             The Response HTTP Status was not 200 OK
 */
public static String HTTPGet(String url) throws InvalidResponseException, HTTPException {
    HttpClient httpclient = new DefaultHttpClient();
    HttpGet httpget = new HttpGet(url);

    HttpResponse response;
    try {
        response = httpclient.execute(httpget);
    } catch (Exception e) {
        throw new HTTPException(e.getMessage(), e);
    }

    if (response.getStatusLine().toString().indexOf("200 OK") == -1) {
        throw new InvalidResponseException("Invalid status: " + response.getStatusLine());
    }

    try {
        return EntityUtils.toString(response.getEntity());
    } catch (Exception e) {
        throw new HTTPException(e.getMessage(), e);
    }
}

From source file:xj.property.ums.common.NetworkUitlity.java

public static MyMessage post(String url, String data) {
    // TODO Auto-generated method stub
    CommonUtil.printLog("ums", url);
    String returnContent = "";
    MyMessage message = new MyMessage();
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);
    try {/* w w  w  .  ja v a 2  s  .c  o m*/
        StringEntity se = new StringEntity(data, HTTP.UTF_8);
        CommonUtil.printLog("postdata", "content=" + data);
        se.setContentType("application/x-www-form-urlencoded");
        httppost.setEntity(se);
        HttpResponse response = httpclient.execute(httppost);
        int status = response.getStatusLine().getStatusCode();
        CommonUtil.printLog("ums", status + "");
        String returnXML = EntityUtils.toString(response.getEntity());
        returnContent = URLDecoder.decode(returnXML);
        switch (status) {
        case 200:
            message.setFlag(true);
            message.setMsg(returnContent);
            break;

        default:
            Log.e("error", status + returnContent);
            message.setFlag(false);
            message.setMsg(returnContent);
            break;
        }
    } catch (Exception e) {
        JSONObject jsonObject = new JSONObject();

        try {
            jsonObject.put("err", e.toString());
            returnContent = jsonObject.toString();
            message.setFlag(false);
            message.setMsg(returnContent);
        } catch (JSONException e1) {
            e1.printStackTrace();
        }

    }
    CommonUtil.printLog("UMSAGENT", message.getMsg());
    return message;
}

From source file:Technique.PostFile.java

public static void upload(String files) throws Exception {

    String userHome = System.getProperty("user.home");
    HttpClient httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    HttpPost httppost = new HttpPost("http://localhost/image/up.php");
    File file = new File(files);
    MultipartEntity mpEntity = new MultipartEntity();
    ContentBody contentFile = new FileBody(file);
    mpEntity.addPart("userfile", contentFile);
    httppost.setEntity(mpEntity);/*w  ww. j av a2 s.c  o m*/
    System.out.println("executing request " + httppost.getRequestLine());
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity resEntity = response.getEntity();

    if (!(response.getStatusLine().toString()).equals("HTTP/1.1 200 OK")) {
        // Successfully Uploaded
    } else {
        // Did not upload. Add your logic here. Maybe you want to retry.
    }
    System.out.println(response.getStatusLine());
    if (resEntity != null) {
        System.out.println(EntityUtils.toString(resEntity));
    }
    if (resEntity != null) {
        resEntity.consumeContent();
    }
    httpclient.getConnectionManager().shutdown();
}