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.alibaba.flink.utils.MetricsMonitor.java

public static Map httpResponse(String url) {
    Map ret;//  w w  w  . jav  a 2s .  c  om
    try {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet getRequest = new HttpGet(url);
        getRequest.addHeader("accept", "application/json");

        HttpResponse response = httpClient.execute(getRequest);

        if (response.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException(
                    "Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
        }

        String data = EntityUtils.toString(response.getEntity());

        ret = (Map) Utils.from_json(data);

        httpClient.getConnectionManager().shutdown();

    } catch (IOException e) {
        ret = errorMsg(e.getMessage());
    }
    return ret;
}

From source file:com.wbtech.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 ww  .  ja va2 s  .c o  m*/
        StringEntity se = new StringEntity("content=" + 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:org.elasticsearch.xpack.test.rest.XPackRestTestHelper.java

/**
 * Waits for the Machine Learning templates to be created
 * and check the version is up to date//from w w w .  j  av a  2s. com
 */
public static void waitForMlTemplates(RestClient client) throws InterruptedException {
    AtomicReference<Version> masterNodeVersion = new AtomicReference<>();
    ESTestCase.awaitBusy(() -> {
        String response;
        try {
            response = EntityUtils.toString(client
                    .performRequest("GET", "/_cat/nodes", singletonMap("h", "master,version")).getEntity());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        for (String line : response.split("\n")) {
            if (line.startsWith("*")) {
                masterNodeVersion.set(Version.fromString(line.substring(2).trim()));
                return true;
            }
        }
        return false;
    });

    final List<String> templateNames = Arrays.asList(AuditorField.NOTIFICATIONS_INDEX, MlMetaIndex.INDEX_NAME,
            AnomalyDetectorsIndex.jobStateIndexName(), AnomalyDetectorsIndex.jobResultsIndexPrefix());
    for (String template : templateNames) {
        ESTestCase.awaitBusy(() -> {
            Map<?, ?> response;
            try {
                String string = EntityUtils
                        .toString(client.performRequest("GET", "/_template/" + template).getEntity());
                response = XContentHelper.convertToMap(JsonXContent.jsonXContent, string, false);
            } catch (ResponseException e) {
                if (e.getResponse().getStatusLine().getStatusCode() == 404) {
                    return false;
                }
                throw new RuntimeException(e);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            Map<?, ?> templateDefinition = (Map<?, ?>) response.get(template);
            return Version.fromId((Integer) templateDefinition.get("version")).equals(masterNodeVersion.get());
        });
    }
}

From source file:shootersubdownloader.Shootersubdownloader.java

private static void down(File f) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    String url = String.format("https://www.shooter.cn/api/subapi.php?filehash=%s&pathinfo=%s&format=json",
            computefilehash(f), f.getName());
    System.out.println(url);/*  ww  w  . ja v  a 2s  .  c  om*/
    HttpGet request = new HttpGet(url);
    CloseableHttpResponse r = httpclient.execute(request);
    System.out.println(r.getStatusLine());
    HttpEntity e = r.getEntity();
    String s = EntityUtils.toString(e);
    System.out.println(s);
    JSONArray json = JSONArray.fromObject(s);
    //        JSONObject json = JSONObject.fromObject(s);
    System.out.println(json.size());
    for (int i = 0; i < json.size(); i++) {
        System.out.println(i);
        JSONObject obj = json.getJSONObject(i);
        JSONArray fs = obj.getJSONArray("Files");
        String downurl = fs.getJSONObject(0).getString("Link");
        HttpGet r2 = new HttpGet(downurl);
        CloseableHttpResponse res2 = httpclient.execute(r2);
        //            Header[] headers = res2.getAllHeaders();
        //            for(Header h:headers){
        //                System.out.println(h.getName());
        //                System.out.println(h.getValue());
        //            }
        Header header = res2.getFirstHeader("Content-Disposition");
        String sig = "filename=";
        String v = header.getValue();
        String fn = v.substring(v.indexOf(sig) + sig.length());
        HttpEntity e2 = res2.getEntity();
        File outf = new File(fn);
        FileOutputStream fos = new FileOutputStream(outf);
        e2.writeTo(fos);

        System.out.println(filecharsetdetect.FileCharsetDetect.detect(outf));
        //            res2.getEntity().writeTo(new FileOutputStream(fn));
        System.out.println(fn);
        res2.close();
    }

    r.close();
    httpclient.close();
}

From source file:it.av.wikipedia.client.WikipediaClient.java

public static String Query(QueryParameters params) {
    try (CloseableHttpClient httpclient = HttpClients.custom()
            .setDefaultRequestConfig(RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build())
            .build()) {//from ww w. j  ava2  s. com
        StringBuilder url = new StringBuilder(ENDPOINT);
        url.append(params.toURLQueryString());

        //System.out.println("GET: " + url);
        HttpGet request = new HttpGet(url.toString());
        request.setHeader("User-Agent", "FACWikiTool");

        // Create a custom response handler
        ResponseHandler<String> responseHandler = (final HttpResponse response) -> {
            int status = response.getStatusLine().getStatusCode();
            if (status >= 200 && status < 300) {
                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity) : null;
            } else {
                throw new ClientProtocolException("Unexpected response status: " + status);
            }
        };

        return httpclient.execute(request, responseHandler);
    } catch (IOException ex) {
        Logger.getLogger(WikipediaClient.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    }
}

From source file:neembuu.release1.settings.OnlineSettingImpl.java

public static String getRaw(String... p) {
    //Get the version.xml and read the version value.
    HttpParams params = new BasicHttpParams();
    params.setParameter("http.useragent",
            "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2) Gecko/20100115 Firefox/3.6");
    DefaultHttpClient httpclient = new DefaultHttpClient(params);
    String pth = "";
    for (String p_ele : p) {
        pth = pth + "/" + p_ele;
    }//from   w ww.  j a  va2s  .  c  om
    HttpGet httpget = new HttpGet("http://neembuu.sourceforge.net" + pth);
    LoggerUtil.L().log(Level.INFO, "Getting online setting ...{0}", p);
    try {
        HttpResponse response = httpclient.execute(httpget);
        String respxml = EntityUtils.toString(response.getEntity());
        return respxml;
    } catch (Exception ex) {
        LoggerUtil.L().log(Level.INFO, "Exception while getting resource " + p, ex);
    }

    return null;
}

From source file:org.elasticsearch.client.ResponseException.java

private static String buildMessage(Response response) throws IOException {
    String message = response.getRequestLine().getMethod() + " " + response.getHost()
            + response.getRequestLine().getUri() + ": " + response.getStatusLine().toString();

    HttpEntity entity = response.getEntity();
    if (entity != null) {
        if (entity.isRepeatable() == false) {
            entity = new BufferedHttpEntity(entity);
            response.getHttpResponse().setEntity(entity);
        }/*  ww w. jav a  2 s. c  o  m*/
        message += "\n" + EntityUtils.toString(entity);
    }
    return message;
}

From source file:manager.computerVisionManager.java

private static void getJson(String path) {
    System.out.println("Get Description from https://westus.api.cognitive.microsoft.com/vision/v1.0/describe");
    try {/*from   w w w  .  j  a  v  a  2  s. co  m*/
        URIBuilder builder = new URIBuilder("https://westus.api.cognitive.microsoft.com/vision/v1.0/describe");
        builder.setParameter("maxCandidates", "1");
        URI uri = builder.build();
        HttpPost request = new HttpPost(uri);
        request.setHeader("Content-Type", "application/json");
        request.setHeader("Ocp-Apim-Subscription-Key", "d7f6ef12e41c4f8c8e72d12a890fa703");
        // Request body
        StringEntity reqEntity = new StringEntity("{\"url\":\"" + path + "\"}");
        System.out.println("Request String: " + reqEntity.toString());
        request.setEntity(reqEntity);
        HttpResponse response = httpclient.execute(request);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            String respuesta = EntityUtils.toString(entity);
            JSONParser lector = new JSONParser();
            StringReader SR = new StringReader(respuesta);
            try {
                JSONObject temp = (JSONObject) lector.parse(SR);
                json = (JSONObject) temp.get("description");
            } catch (org.json.simple.parser.ParseException e) {
                System.err.println(e.getMessage());
            }
        }
    } catch (IOException | URISyntaxException | ParseException e) {
        System.err.println(e.getMessage());
    }
}

From source file:neembuu.uploader.versioning.CheckUser.java

public static void getCanCustomizeNormalizing(UserSetPriv usp) {
    boolean canCustomizeNormalizing = true;
    String normalization = ".neembuu";
    HttpParams params = new BasicHttpParams();
    params.setParameter("http.useragent",
            "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2) Gecko/20100115 Firefox/3.6");
    HttpClient httpclient = NUHttpClient.getHttpClient();
    HttpGet httpget = new HttpGet("http://neembuu.com/uploader/api/user.xml?userid=" + UserImpl.I().uid());
    NULogger.getLogger().info("Checking for user priviledges ...");
    try {/*  w  w  w.  j a  va  2 s. c  om*/
        HttpResponse response = httpclient.execute(httpget);
        String respxml = EntityUtils.toString(response.getEntity());
        canCustomizeNormalizing = getCanCustomizeNormalizingFromXml(respxml);
        normalization = getNormalization(respxml);
        NULogger.getLogger().log(Level.INFO, "CanCustomizeNormalizing: {0}", canCustomizeNormalizing);
    } catch (Exception ex) {
        NULogger.getLogger().log(Level.INFO, "Exception while checking update\n{0}", ex);
    }
    usp.setCanCustomizeNormalizing(canCustomizeNormalizing);
    usp.setNormalization(normalization);
}

From source file:net.wespot.pim.TestingClass.java

public static String answers(String token, long inquiryId) {
    PropertiesAdapter pa = PropertiesAdapter.getInstance();
    HttpConnection conn = ConnectionFactory.getConnection();
    token = pa.getAuthToken();/* w  ww  .ja  v  a  2s.com*/
    String url = getUrlPrefix();
    url += "&api_key=" + INQ.config.getProperty("elgg_api_key") + "&inquiryId=" + inquiryId
            + "&method=inquiry.answers";
    HttpResponse response = conn.executeGET(url, token, "application/json");
    try {
        //            return EntityUtils.toString(response.getEntity());
        JSONObject json = new JSONObject(EntityUtils.toString(response.getEntity()));
        return json.toString();
    } catch (Exception e) {
        if (e instanceof ARLearnException)
            throw (ARLearnException) e;

    }
    return "error";
}