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:eu.riscoss.rdc.GithubAPI_Test.java

/**
 * GIT API Test method //from w ww  .  j  a v  a 2s .  c  om
 * @param req
 * @return
 */
static JSONArray gitJSONGetter() {
    String json = "";
    //String repository = values.get("repository");

    String owner = "RISCOSS/";
    //String repo = "riscoss-analyser/";
    String repo = "riscoss-data-collector/";

    String r = owner + repo;

    String req;
    req = r + "commits";

    //NST: needs some time to be calculated. 1st time it returns Status 202!
    req = r + "stats/contributors"; //NST single contributors with weekly efforts: w:week, a:add, d:del, c:#commits

    //https://developer.github.com/v3/repos/statistics/#commit-activity
    req = r + "stats/commit_activity";//NST data per week (1y):  The days array is a group of commits per day, starting on Sunday.

    req = r + "collaborators"; //needs authorization! Error 401

    req = r + "events"; //committs and other events. Attention: max 10x30 events, max 90days!

    req = r + "issues?state=all"; //all issues. Of interest: state=open, closed, 

    //      req = r + "stats/participation";//NST  weekly commit count

    //req = r + "stats/code_frequency";  //NST: week,  number of additions, number of deletions per week

    //HttpGet( "https://api.github.com/rate_limit");  //rate limit is 60 requests per hour!!
    /**
     * TODO:
     * participation: week list, analysis value
     * issues open, issues closed today status
     *  
     */

    HttpGet get = new HttpGet("https://api.github.com/repos/" + req);
    //get = new HttpGet( "https://api.github.com/rate_limit");

    //only for getting the License
    //get.setHeader("Accept", "application/vnd.github.drax-preview+json");

    HttpResponse response;
    try {
        response = client.execute(get);

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

        } else if (response.getStatusLine().getStatusCode() == 202) {
            System.err.println("WARNING 202 Accept: Computing....try again in some seconds.");
            return null;
        } else {
            // something has gone wrong...
            System.err.println(response.getStatusLine().getStatusCode());
            System.err.println(response.getStatusLine().toString());
            return null;
        }
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    System.out.println("****JSON****\n" + json + "\n************");

    try {
        JSONAware jv = (JSONAware) new JSONParser().parse(json);

        if (jv instanceof JSONObject) {
            JSONObject jo = (JSONObject) jv;
            System.out.println("JO: ");
            for (Object o : jo.entrySet()) {
                System.out.println("\t" + o);
            }

        }

        if (jv instanceof JSONArray) {
            JSONArray ja = (JSONArray) jv;

            int size = ja.size();
            System.out.println("JA Size = " + size);
            for (Object o : ja) {
                if (o instanceof JSONObject) {
                    JSONObject jo = (JSONObject) o;
                    System.out.println("JA Object:");
                    for (Object o2 : jo.entrySet()) {
                        System.out.println("\t" + o2);
                    }
                } else {
                    System.out.println("JA Array: " + (JSONArray) o);
                }
            }
            return ja;
        }

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

From source file:models.ApiConnectorPromotions.java

public JSONArray GetAllTeas() {
    String url = "http://chuangmi.my-place.us/getAllPromotionInfo.php";

    /*/*  w  ww .  ja v  a2  s .  com*/
     * Get HttpResponse object from the url
     * Get HttpEntity from Http Response object
     */

    HttpEntity httpEntity = null;

    try {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);

        HttpResponse httpResponse = httpClient.execute(httpGet);

        httpEntity = httpResponse.getEntity();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    //convert HttpEntity into JSON array
    JSONArray jsonArray = null;

    if (httpEntity != null) {
        try {
            String entityResponse = EntityUtils.toString(httpEntity);
            Log.e("Entity Response : ", entityResponse);
            jsonArray = new JSONArray(entityResponse);
        } catch (JSONException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return jsonArray;
}

From source file:de.vanita5.twittnuker.task.HototinAsyncTask.java

protected void doExpand(final String url) {
    final String finalUrl = HOTOT_URL + url.replace("http://hotot.in/", "") + ".json";

    Thread thread = new Thread() {

        @Override/*from  ww  w .  j av  a2s .  co m*/
        public void run() {
            try {
                HttpClient httpClient = HttpClientFactory.getThreadSafeClient();
                HttpResponse response = httpClient.execute(new HttpGet(finalUrl));

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

                JSONObject jsonObject = new JSONObject(sResponse);

                String result = jsonObject.getString(HOTOT_ENTITY_FULL_TEXT);

                final Intent intent = new Intent(BROADCAST_HOTOTIN_EXPANDED);
                intent.putExtra(EXTRA_HOTOTIN_EXPANDED_TEXT, result);
                mContext.sendBroadcast(intent);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };
    thread.start();
}

From source file:HttpConnections.RestConnFactory.java

public ResponseContents RestRequest(HttpRequestBase httprequest) throws IOException {
    HttpResponse httpResponseTemp = null;
    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, 30000);
    HttpConnectionParams.setSoTimeout(httpParams, 30000);
    this.httpclient = new DefaultHttpClient(httpParams);

    try {//w  w  w .  j a  v  a2 s. co m
        httpResponseTemp = this.httpclient.execute(httprequest);
    } catch (IOException ex) {
        System.out.println("An error occured while executing the request. Message: " + ex);
        this.responseObj.setContents(ex.toString());
    } finally {
        if (httpResponseTemp != null) {
            this.httpResponse = httpResponseTemp;
            this.responseObj.setStatus(this.httpResponse.getStatusLine().toString());
            if (this.httpResponse.getEntity() == null
                    || this.httpResponse.getStatusLine().toString().contains("500")) {
                this.responseObj.setContents("No Content");
            } else {
                this.responseObj.setContents(EntityUtils.toString(this.httpResponse.getEntity()));
            }
        }
        this.httpclient.close();
        return this.responseObj;
    }
}

From source file:net.orzo.data.Web.java

/**
 *
 *///from   www. j  a va 2  s. c  o  m
public String get(String URL) {
    HttpGet httpget = new HttpGet(URL);
    CloseableHttpResponse response = null;
    HttpEntity httpEntity;
    String result = null;

    try {
        response = this.httpClient.execute(httpget);
        httpEntity = response.getEntity();
        if (httpEntity != null) {
            httpEntity = new BufferedHttpEntity(httpEntity);
            result = EntityUtils.toString(httpEntity);
        }

    } catch (IOException e) {
        throw new RuntimeException(e);

    } finally {
        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
                LOG.warn(String.format("Failed to close response object: %s", e));
            }
        }
    }
    return result;
}

From source file:api.HTTPCommandStatus.java

/**
 * Set the content from the web service.
 * @param entity can be JSON, XML plain text what have you.
 *///from   w w w. j  a  va 2s.  co  m
void setEntity(HttpEntity entity) {
    String content = "";
    try {
        content = EntityUtils.toString(entity);
    } catch (IOException ex) {
        status = ResponseTypes.CONFIG_ERROR;
        System.out.println(ex.getMessage());
    } catch (ParseException ex) {
        status = ResponseTypes.ERROR;
        System.out.println(ex.getMessage());
    }
    this.stdout.append(content);
}

From source file:ar.edu.ubp.das.src.chat.actions.ValidAction.java

@Override
public ForwardConfig execute(ActionMapping mapping, DynaActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws SQLException, RuntimeException {
    try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
        HttpPost httpPost = new HttpPost("http://25.136.78.82:8080/login/");
        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("nombre_usuario", form.getItem("user")));
        params.add(new BasicNameValuePair("password", form.getItem("pw")));
        httpPost.setEntity(new UrlEncodedFormEntity(params));
        CloseableHttpResponse postResponse = httpClient.execute(httpPost);

        HttpEntity responseEntity = postResponse.getEntity();
        StatusLine responseStatus = postResponse.getStatusLine();
        String restResp = EntityUtils.toString(responseEntity);

        if (responseStatus.getStatusCode() != 200) {
            System.out.println(restResp);
            throw new RuntimeException("Los datos ingresados son incorrectos");
        }//from  www .  j a va2s  . c  om

        Header authHeader = postResponse.getFirstHeader("Auth-Token");
        String headerValue = authHeader != null ? authHeader.getValue() : "";

        HttpPost adminPost = new HttpPost("http://25.136.78.82:8080/login/admin");
        adminPost.addHeader("Authorization", "BEARER " + headerValue);
        adminPost.addHeader("accept", "application/json");

        postResponse = httpClient.execute(adminPost);
        responseEntity = postResponse.getEntity();
        responseStatus = postResponse.getStatusLine();

        if (responseStatus.getStatusCode() != 200) {
            throw new RuntimeException("Accesso restringido a Administradores");
        }

        request.getSession().setAttribute("user", restResp);
        request.getSession().setAttribute("token", headerValue);
        request.getSession().setAttribute("login_tmst", String.valueOf(System.currentTimeMillis()));

        return mapping.getForwardByName("success");

    } catch (IOException | RuntimeException e) {
        request.setAttribute("message", "Error al realizar login: " + e.getMessage());
        response.setStatus(401);
        return mapping.getForwardByName("failure");
    }
}

From source file:org.keycloak.testsuite.saml.AuthnRequestTest.java

@Test
public void testIsForceAuthNotSet() throws Exception {
    String res = new SamlClientBuilder().authnRequest(getAuthServerSamlEndpoint(REALM_NAME),
            SAML_CLIENT_ID_SALES_POST, SAML_ASSERTION_CONSUMER_URL_SALES_POST, Binding.POST)
            .transformObject(so -> {//from   w w w  .  jav  a 2 s . c o m
                so.setForceAuthn(null);
                return so;
            }).build()

            .executeAndTransform(resp -> EntityUtils.toString(resp.getEntity()));

    assertThat(res, containsString("login"));
}

From source file:io.djigger.monitoring.java.instrumentation.subscription.HttpClientTracerTest.java

private String parseResponse(CloseableHttpResponse response) throws Exception {

    String responseString = EntityUtils.toString(response.getEntity());
    return responseString;

}

From source file:org.apache.camel.component.restlet.RestletExceptionResponseTest.java

@Test
public void testExceptionResponse() throws Exception {
    HttpResponse response = doExecute(new HttpPost("http://localhost:" + portNum + "/users/homer"));
    String body = EntityUtils.toString(response.getEntity());

    assertHttpResponse(response, 500, "text/plain");
    assertTrue(body.contains("IllegalArgumentException"));
    assertTrue(body.contains("Damn something went wrong"));
}