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:Onlinedata.MainSendRequest.java

public void downloadData(String filename) {
    downloadurl = baseurl + filename;//w  w  w .  jav a2  s .c  om
    try {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpget = new HttpGet(downloadurl);
        CloseableHttpResponse response = httpclient.execute(httpget);
        try {
            response = httpclient.execute(httpget);
            HttpEntity serverEntity = response.getEntity();
            if (serverEntity != null) {
                System.out.println("Found file at adress: " + downloadurl);
                long len = serverEntity.getContentLength();
                System.out.println("Length is " + len);
                download = EntityUtils.toString(serverEntity);
                System.out.println(download);
            }
        } catch (IOException | ParseException ex) {
            Logger.getLogger(MainSendRequest.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            response.close();
        }
        httpclient.close();
    } catch (IOException ex) {
        Logger.getLogger(MainSendRequest.class.getName()).log(Level.SEVERE, null, ex);
    }

}

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

@Override
public ForwardConfig execute(ActionMapping mapping, DynaActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws SQLException, RuntimeException {
    try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
        String authToken = String.valueOf(request.getSession().getAttribute("token"));

        HttpPost httpPost = new HttpPost("http://25.136.78.82:8080/logout/");
        httpPost.addHeader("Authorization", "BEARER " + authToken);
        httpPost.addHeader("accept", "application/json");

        CloseableHttpResponse postResponse = httpClient.execute(httpPost);

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

        if (responseStatus.getStatusCode() != 200) {
            throw new RuntimeException(restResp);
        }//from  w w  w. j a  v a  2  s  .com

        request.getSession().removeAttribute("token");

        return mapping.getForwardByName("success");

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

From source file:org.factpub.ui.gui.network.PostFile.java

public static List<String> uploadToFactpub(File file) throws Exception {
    List<String> status = new ArrayList<String>();
    int i = 0;//from ww  w . j  ava2 s .  c o  m

    HttpClient httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

    String postUrl = FEConstants.SERVER_POST_HANDLER + "?id=" + AuthMediaWikiIdHTTP.authorisedUser + "&ps="
            + AuthMediaWikiIdHTTP.userPassword;

    HttpPost httppost = new HttpPost(postUrl);

    System.out.println(postUrl);

    MultipartEntity mpEntity = new MultipartEntity();
    ContentBody cbFile = new FileBody(file, "json");

    // name must be "uploadfile". this is same on the server side.
    mpEntity.addPart(FEConstants.SERVER_UPLOAD_FILE_NAME, cbFile);

    httppost.setEntity(mpEntity);
    System.out.println("executing request " + httppost.getRequestLine());
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity resEntity = response.getEntity();

    System.out.println(response.getStatusLine());

    if (response.getStatusLine().toString().contains("502 Bad Gateway")) {
        status.add("Looks server is down.");
    } else {
        if (resEntity != null) {
            status.add(EntityUtils.toString(resEntity));
            System.out.println(status.get(i));
            i++;
        }

        if (resEntity != null) {
            resEntity.consumeContent();
        }
    }
    httpclient.getConnectionManager().shutdown();

    //String status = "Upload Success!";
    return status;
}

From source file:com.helpers.ServiceLocationsHelper.java

public static String getLocations(String opportunityId) throws Exception {
    String accountId = getAccountId(opportunityId);

    final String soql = "SELECT+Id,Name,pricesenz__Account__c,pricesenz__Door_Number__c,pricesenz__Street_Name__c,pricesenz__City__c,pricesenz__State__c+FROM+pricesenz__Service_Location__c+where+pricesenz__Account__c+=+'"
            + accountId + "'";

    HttpClient httpClient = HttpClientBuilder.create().build();
    if (loginInstanceUrl == null) {
        try {/* ww  w . ja  v a  2 s . c  o m*/
            LoginHelper.getAccessToken("");
        } catch (Exception ex) {
        }
    }
    baseUri = loginInstanceUrl + SOAP_ENDPOINT;
    oauthHeader = new BasicHeader("Authorization", "Bearer " + accessToken);

    String uri = baseUri + "/query?q=" + soql;
    //        System.out.println("Query URL: " + uri);
    HttpGet httpGet = new HttpGet(uri);
    httpGet.addHeader(oauthHeader);
    httpGet.addHeader(prettyPrintHeader);

    // Make the request.
    HttpResponse httpResponse = httpClient.execute(httpGet);
    String getResponse = EntityUtils.toString(httpResponse.getEntity());
    //        System.out.println("Query Result:\n" + getResponse);
    return getResponse;
}

From source file:com.savvywits.wethepeople.RESTService.java

@Override
protected void onHandleIntent(Intent intent) {
    Bundle extras = intent.getExtras();/*from  w  w  w.ja v a 2  s .c om*/
    ResultReceiver receiver = extras.getParcelable("receiver");
    String data = extras.getString("zipcode");
    String url = ZIP_CODE_BASE + data;

    Bundle bundle = new Bundle();
    receiver.send(STATUS_RUNNING, Bundle.EMPTY);
    try {
        String json = EntityUtils.toString(new DefaultHttpClient().execute(new HttpGet(url)).getEntity());

        if (!validateJSON(json)) {
            receiver.send(STATUS_ERROR, Bundle.EMPTY);
        } else {
            bundle.putString("rest_result", json);
            receiver.send(STATUS_FINISHED, bundle);
        }
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        bundle.putString(Intent.EXTRA_TEXT, e.toString());
        receiver.send(STATUS_ERROR, bundle);
    }
}

From source file:com.rastating.droidbeard.net.ErrorReportTask.java

public JSONObject postData(String url, JSONObject obj) {
    HttpClient client = new DefaultHttpClient();
    String json = obj.toString();

    try {/*w w  w . j  a  v a 2 s  .  com*/
        HttpPost post = new HttpPost(url);
        post.setHeader("Content-type", "application/json");

        StringEntity se = new StringEntity(obj.toString());
        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        post.setEntity(se);

        HttpResponse response = client.execute(post);
        String retval = EntityUtils.toString(response.getEntity());

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

From source file:jp.co.gui.aruga.watch.ClockHttpRequest.java

public List<Todo> get(String category) throws IOException {
    String jsonUrl = url + "/json";
    if (category != null)
        jsonUrl = jsonUrl + "?category=" + category;
    HttpGet request = new HttpGet(jsonUrl);

    HttpResponse hr = httpClient.execute(request);
    String result = EntityUtils.toString(hr.getEntity());
    List<TodoResponse> todo = om.readValue(result, new TypeReference<List<TodoResponse>>() {
    });//from  w w w .ja  v  a2  s .  c  o m
    List<Todo> listT = new ArrayList<>();
    for (TodoResponse todo1 : todo) {
        listT.add(todo1.getTodo());
    }
    return listT;
}

From source file:cn.loveapple.client.android.util.ApiUtil.java

public static String getHttpBody(String url, PackageManager packageManager) {
    if (StringUtils.isEmpty(url)) {
        return null;
    }/*w  ww  . j a va2s.  com*/

    String body = null;
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpParams params = httpClient.getParams();
    // SYSTEM INFO
    params.setParameter("", "");
    params.setParameter("", "");
    params.setParameter("", "");
    HttpConnectionParams.setConnectionTimeout(params, 1000);
    HttpConnectionParams.setSoTimeout(params, 1000);
    HttpPost httpRequest = new HttpPost(url);
    HttpResponse httpResponse = null;

    try {
        httpResponse = httpClient.execute(httpRequest);
    } catch (Exception e) {
        Log.e(LOG_TAG, "http response execute failed.", e);
        return null;
    }
    if (httpResponse != null && httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        HttpEntity httpEntity = httpResponse.getEntity();

        try {
            body = EntityUtils.toString(httpEntity);
        } catch (Exception e) {
            Log.e(LOG_TAG, "get http response body failed.", e);
            return null;
        } finally {
            try {
                httpEntity.consumeContent();
            } catch (IOException e) {
            }
        }
    }
    httpClient.getConnectionManager().shutdown();

    return body;
}

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

public static String getRequest(final String url, String token, final boolean isSingleton) throws Exception {
    String json = null;/* ww  w . j av  a  2 s .c  o  m*/
    HttpClient client = HttpClientManager.getHttpClient(isSingleton);
    HttpEntity resEntity = null;
    HttpGet get = new HttpGet(url);
    if (Validator.isNotEmpty(token)) {
        get.addHeader("token", token);
    }

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

        if (resEntity != null) {
            try {
                resEntity.consumeContent();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        client.getConnectionManager().closeExpiredConnections();
    }
    return json;
}

From source file:org.sharetask.controller.DummyControllerIT.java

@Test
public void testIfAppIsUp() throws IOException {
    //given/* w  w w  .  j av  a 2s  . c  o m*/
    HttpClient client = new DefaultHttpClient();
    HttpGet httpget = new HttpGet(URL);

    //when
    HttpResponse response = client.execute(httpget);

    //then
    Assert.assertEquals(HttpStatus.OK.value(), response.getStatusLine().getStatusCode());
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        String result = EntityUtils.toString(entity);
        Assert.assertEquals("OK", result);
    } else {
        Assert.fail("No content!");
    }
}