Example usage for org.apache.http.client.methods HttpGet toString

List of usage examples for org.apache.http.client.methods HttpGet toString

Introduction

In this page you can find the example usage for org.apache.http.client.methods HttpGet toString.

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the object.

Usage

From source file:fridgegameinstaller.MCJsonConf.java

public static void getJson(String path, int mb) throws IOException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet httpGet = new HttpGet("http://api.fridgegame.com/mcconf/Fridgegame.json");

    CloseableHttpResponse response1 = httpclient.execute(httpGet);
    try {//from w w w .ja  v a  2s.  co m
        System.out.println(httpGet.toString());
        System.out.println(response1.getStatusLine());
        BufferedReader br = new BufferedReader(new InputStreamReader(response1.getEntity().getContent()));
        String a;
        String output = "";
        while ((a = br.readLine()) != null) {
            output += a + "\n";
        }
        System.out.println(output);
        try {

            JSONObject json = new JSONObject(output);
            String mcArgs = json.getString("minecraftArguments");
            String regex = "(-Xmx[^ ]*)";
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(mcArgs);
            String newArgs = m.replaceAll("-Xmx" + mb + "M");
            json.put("minecraftArguments", newArgs);
            FileWriter file = new FileWriter(path);

            try {
                file.write(json.toString());

            } catch (IOException e) {
                e.printStackTrace();

            } finally {
                file.flush();
                file.close();
            }

        } catch (JSONException e) {

        }
    } finally {
        response1.close();
    }

}

From source file:net.okjsp.imageloader.ImageFetcher.java

/**
 * Download a bitmap from a URL, write it to a disk and return the File pointer. This
 * implementation uses a simple disk cache.
 *
 * @param context The context to use//ww w .  jav  a 2 s  . co  m
 * @param urlString The URL to fetch
 * @return A File pointing to the fetched bitmap
 */
public static File downloadBitmap(Context context, String urlString) {
    final File cacheDir = DiskLruCache.getDiskCacheDir(context, HTTP_CACHE_DIR);

    final DiskLruCache cache = DiskLruCache.openCache(context, cacheDir, HTTP_CACHE_SIZE);

    final File cacheFile = new File(cache.createFilePath(urlString));

    if (cache.containsKey(urlString)) {
        if (BuildConfig.DEBUG && DEBUG_LOG) {
            Log.d(TAG, "downloadBitmap - found in http cache - " + urlString);
        }
        return cacheFile;
    }

    if (BuildConfig.DEBUG && DEBUG_LOG) {
        Log.d(TAG, "downloadBitmap - downloading - " + urlString);
    }

    ImageLoaderUtils.disableConnectionReuseIfNecessary();
    BufferedOutputStream out = null;
    InputStream in = null;
    final DefaultHttpClient client = new DefaultHttpClient();
    final HttpGet getRequest = new HttpGet(urlString);

    try {
        if (DEBUG_LOG)
            Log.d(TAG, "getRequest:" + getRequest.toString());
        HttpResponse response = client.execute(getRequest);
        final int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            return null;
        }

        final HttpEntity entity = response.getEntity();
        if (entity != null) {
            in = new BufferedInputStream(entity.getContent(), ImageLoaderUtils.IO_BUFFER_SIZE);
        }
        out = new BufferedOutputStream(new FileOutputStream(cacheFile), ImageLoaderUtils.IO_BUFFER_SIZE);

        int b;
        while ((b = in.read()) != -1) {
            out.write(b);
        }

        in.close();
        in = null;

        return cacheFile;

    } catch (final IOException e) {
        e.printStackTrace();
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            in = null;
        }

        if (out != null) {
            try {
                out.close();
            } catch (final IOException e) {
                e.printStackTrace();
            }
        }
    }

    return null;
}

From source file:org.wso2.cdm.agent.proxy.ServerApiAccess.java

public static Map<String, String> postData(APIUtilities apiUtilities, Map<String, String> headers) {
    String httpMethod = apiUtilities.getHttpMethod();
    String url = apiUtilities.getEndPoint();
    JSONObject params = apiUtilities.getRequestParams();
    Map<String, String> responseParams = new HashMap<String, String>();
    HttpClient httpclient = getCertifiedHttpClient();

    if (httpMethod.equals("POST")) {
        HttpPost httpPost = new HttpPost(url);
        if (params != null) {
            try {
                httpPost.setEntity(new StringEntity(params.toString()));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();/*w  ww  . j av a2  s  . c  om*/
            }
        } else {
            httpPost.setEntity(null);
        }
        Log.e("url", "" + url);
        HttpPost httpPostWithHeaders = (HttpPost) buildHeaders(httpPost, headers, httpMethod);
        try {
            HttpResponse response = httpclient.execute(httpPostWithHeaders);
            String status = String.valueOf(response.getStatusLine().getStatusCode());
            Log.d(TAG, status);
            responseParams.put("response", getResponseBody(response));
            responseParams.put("status", status);
            return responseParams;
        } catch (ClientProtocolException e) {
            Log.d(TAG, "ClientProtocolException :" + e.toString());
            return null;
        } catch (IOException e) {
            Log.d(TAG, e.toString());
            responseParams.put("response", "Internal Server Error");
            responseParams.put("status", "500");
            return responseParams;
        }
    } else if (httpMethod.equals("GET")) {
        //          if(payload!=null){
        //             url = url+"?"+payload;
        //          }
        HttpGet httpGet = new HttpGet(url);
        HttpGet httpGetWithHeaders = (HttpGet) buildHeaders(httpGet, headers, httpMethod);
        Log.d(TAG, httpGetWithHeaders.toString() + " GET");
        try {
            HttpResponse response = httpclient.execute(httpGetWithHeaders);
            responseParams.put("response", getResponseBody(response));
            responseParams.put("status", String.valueOf(response.getStatusLine().getStatusCode()));
            return responseParams;
        } catch (ClientProtocolException e) {
            Log.d(TAG, "ClientProtocolException :" + e.toString());
            return null;
        } catch (IOException e) {
            Log.d(TAG, e.toString());
            responseParams.put("response", "Internal Server Error");
            responseParams.put("status", "500");
            return responseParams;
        }
    }
    return null;
}

From source file:com.fatminds.cmis.AlfrescoCmisHelper.java

public static JsonNode getJsonNodeFromHttpGetResponse(String proto, String host, int port, String user,
        String pass, String path, HashMap params) throws ClientProtocolException, IOException {
    DefaultHttpClient client = new DefaultHttpClient();
    try {/*  w  w w . j a va  2  s.c om*/
        client.getCredentialsProvider().setCredentials(new AuthScope(host, port),
                new UsernamePasswordCredentials(user, pass));
        String paramStr = "";
        if (params != null && params.size() > 0) {
            Iterator<String> iter = params.keySet().iterator();
            while (iter.hasNext()) {
                String key = iter.next();
                //get.getParams().setParameter(key, params.get(key));
                if (!paramStr.equals("")) {
                    paramStr += "&";
                }
                paramStr += key + "=" + params.get(key);
            }
        }

        if (!paramStr.equals("")) {
            path += "?" + URLEncoder.encode(paramStr, "UTF-8").replace("+", "%20");
        }
        HttpGet get = new HttpGet(proto + host + ":" + port + path);
        log.info("Getting JsonNode for " + get.toString());
        HttpResponse resp = client.execute(get);
        if (resp.getStatusLine().getStatusCode() != 200) {
            throw new RuntimeException(
                    "Get failed, can't build JsonNode because: " + resp.getStatusLine().getReasonPhrase());
        }
        org.apache.http.HttpEntity entity = resp.getEntity();
        return mapper.readValue(entity.getContent(), JsonNode.class);
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:de.schneider.dev.poi.service.OpenStreetMapGeoService.java

public void getGeoCoordinate(String location) throws EncoderException {

    LOG.info("Start GeoCoordination OpenStreetMap");

    // create default HttpClient
    HttpClient httpClient = new DefaultHttpClient();

    // get data from URI
    URLCodec urlCodec = new URLCodec("UTF-8");
    HttpGet httpGet = new HttpGet(URI_String + urlCodec.encode(location) + "&format=json");
    LOG.info("HttpGet: " + httpGet);
    LOG.debug(httpGet.toString());
    LOG.debug("HttpGetURI: " + httpGet.getURI());

    // get response
    try {//from  ww  w  .j  a  v  a  2s. c o  m
        HttpResponse httpResponse = httpClient.execute(httpGet);
        LOG.info("HttpResponse: " + httpResponse);
        LOG.info("Status Code: " + httpResponse.getStatusLine().getStatusCode());
        LOG.info("Status Phrase: " + httpResponse.getStatusLine().getReasonPhrase());

        HttpEntity httpEntity = httpResponse.getEntity();
        LOG.info("HttpEntity: " + httpEntity);
        LOG.info("HttpEntity Streaming: " + httpEntity.isStreaming());
        if (httpEntity.isStreaming()) {
            InputStream inputStream = httpEntity.getContent();
            String content = EntityUtils.toString(httpEntity);
            LOG.info(content);
            inputStream.close();
        }

    } catch (ClientProtocolException cpe) {
        LOG.error(cpe.getMessage());
    } catch (IOException ioe) {
        LOG.error(ioe.getMessage());
    }
}

From source file:nl.nn.adapterframework.http.HttpResponseMock.java

public InputStream doGet(HttpHost host, HttpGet request, HttpContext context) {
    assertEquals("GET", request.getMethod());
    StringBuilder response = new StringBuilder();
    String lineSeparator = System.getProperty("line.separator");
    response.append(request.toString() + lineSeparator);

    Header[] headers = request.getAllHeaders();
    for (Header header : headers) {
        response.append(header.getName() + ": " + header.getValue() + lineSeparator);
    }/*  w  ww .  j av  a2s .  c o  m*/

    return new ByteArrayInputStream(response.toString().getBytes());
}

From source file:eu.masconsult.bgbanking.banks.procreditbank.ProcreditClient.java

@Override
public List<RawBankAccount> getBankAccounts(String authtoken)
        throws IOException, ParseException, AuthenticationException {

    DefaultHttpClient httpClient = getHttpClient(authtoken);

    // Create an array that will hold the server-side account
    final ArrayList<RawBankAccount> bankAccounts = new ArrayList<RawBankAccount>();

    // Get the accounts list
    Log.i(TAG, "Getting from: " + GET_BANK_ACCOUNTS_URI);
    final HttpGet get = new HttpGet(GET_BANK_ACCOUNTS_URI);
    get.setHeader("Accept", "*/*");

    Log.v(TAG, "sending " + get.toString());
    final HttpResponse resp = httpClient.execute(get);

    if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
        String response = EntityUtils.toString(resp.getEntity());
        Log.v(TAG, "response = " + response);
        // Our request to the server was successful, now we need to parse
        // the result
        Document doc = Jsoup.parse(response, BASE_URL);

        for (Element row : doc.getElementsByTag("table").get(0).getElementsByTag("tbody").get(0)
                .getElementsByTag("tr")) {
            RawBankAccount bankAccount = obtainBankAccountFromHtmlTableRow(row);
            if (bankAccount != null) {
                bankAccounts.add(bankAccount);
            }/*from w w  w  .  j a v a 2  s .  c o  m*/
        }
    } else if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) {
        // TODO: validate session has expired
        Log.e(TAG, "Authentication exception in getting bank accounts");
        throw new AuthenticationException("session has expired");
    } else {
        throw new ParseException("status after get accounts: " + resp.getStatusLine().getStatusCode() + " "
                + resp.getStatusLine().getReasonPhrase());
    }

    return bankAccounts;
}

From source file:org.esipfed.eskg.aquisition.PODAACWebServiceClient.java

private ByteArrayInputStream executePODAACQuery(String queryString) throws IOException {
    HttpClient client = HttpClientBuilder.create().build();
    HttpGet request = new HttpGet(queryString);

    // add request header
    request.addHeader("User-Agent", "ESKG PO.DAAC WebService Client");
    LOG.info("Executing: {}", request.toString());
    HttpResponse response = client.execute(request);

    LOG.info("Response Code : {}", response.getStatusLine().getStatusCode());

    BufferedReader rd = new BufferedReader(
            new InputStreamReader(response.getEntity().getContent(), Charset.defaultCharset()));

    StringBuilder result = new StringBuilder();
    String line;/*from ww w .j  av a2  s. com*/
    while ((line = rd.readLine()) != null) {
        result.append(line);
    }
    return new ByteArrayInputStream(result.toString().getBytes(StandardCharsets.UTF_8));

}

From source file:eu.masconsult.bgbanking.banks.dskbank.DskClient.java

@Override
public List<RawBankAccount> getBankAccounts(String authToken)
        throws IOException, ParseException, AuthenticationException {
    String uri = BASE_URL + "?" + URLEncodedUtils.format(
            Arrays.asList(new BasicNameValuePair(XML_ID, LIST_ACCOUNTS_XML_ID)), ENCODING) + "&" + authToken;

    // Get the accounts list
    Log.i(TAG, "Getting from: " + uri);
    final HttpGet get = new HttpGet(uri);
    get.setHeader("Accept", "*/*");

    DefaultHttpClient httpClient = getHttpClient();

    Log.v(TAG, "sending " + get.toString());
    final HttpResponse resp = httpClient.execute(get);

    if (resp.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        throw new ParseException("getBankAccounts: unhandled http status "
                + resp.getStatusLine().getStatusCode() + " " + resp.getStatusLine().getReasonPhrase());
    }//  ww w.j a v  a 2 s .c o  m

    HttpEntity entity = resp.getEntity();
    Document doc = Jsoup.parse(entity.getContent(), "utf-8", BASE_URL);

    if (!checkLoggedIn(doc)) {
        throw new AuthenticationException("session expired!");
    }

    Element content = doc.getElementById("PageContent");
    if (content == null) {
        throw new ParseException("getBankAccounts: can't find PageContent");
    }

    Elements tables = content.getElementsByTag("table");
    if (tables == null || tables.size() == 0) {
        throw new ParseException("getBankAccounts: can't find table in PageContent");
    }

    Elements rows = tables.first().getElementsByTag("tr");
    if (rows == null || rows.size() == 0) {
        throw new ParseException("getBankAccounts: first table is empty in PageContent");
    }

    ArrayList<RawBankAccount> bankAccounts = new ArrayList<RawBankAccount>(rows.size());

    String lastCurrency = null;
    for (Element row : rows) {
        RawBankAccount bankAccount = obtainBankAccountFromHtmlTableRow(row);
        if (bankAccount != null) {
            if (bankAccount.getCurrency() == null) {
                bankAccount.setCurrency(lastCurrency);
            } else {
                lastCurrency = bankAccount.getCurrency();
            }
            bankAccounts.add(bankAccount);
        }
    }

    return bankAccounts;
}

From source file:org.picketlink.test.trust.servlet.GatewayServlet.java

private void forwardCall(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {

    String serviceServerUrl = req.getParameter(SERVICE_SERVER_URL);
    if (serviceServerUrl == null) {
        serviceServerUrl = "http://localhost:8080/service/incoming";
    }/*from w  w w  .  j  a  va2  s .c  om*/
    log.debug("serviceServerUrl=" + serviceServerUrl);

    String sCompress = req.getParameter(TOKEN_COMPRESSION_PARAM);
    boolean compress = Boolean.parseBoolean(sCompress);
    log.debug("compress=" + compress);

    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {
        HttpGet httpget = new HttpGet(serviceServerUrl);
        String samlToken = getSamlToken().getAssertionAsString();
        log.debug("samlToken from subject=" + samlToken);
        int options = Base64.NO_OPTIONS;
        if (compress) {
            options = Base64.GZIP;
        }

        String encodedToken = Base64.encodeBytes(samlToken.getBytes(), options | Base64.DONT_BREAK_LINES);
        log.debug("encodedToken=" + encodedToken);

        httpget.addHeader(AUTH_HEADER, "token=\"" + encodedToken + "\"");
        HttpResponse response = httpclient.execute(httpget);
        log.debug("Httpget: " + httpget.toString());
        log.debug("Response: " + response.getStatusLine());
        HttpEntity entity = response.getEntity();

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        entity.writeTo(baos);
        baos.close();
        resp.getOutputStream().write(baos.toByteArray());

    } catch (Exception e) {
        e.printStackTrace(resp.getWriter());
    } finally {
        httpclient.getConnectionManager().shutdown();
    }

}