Example usage for java.net URLEncoder encode

List of usage examples for java.net URLEncoder encode

Introduction

In this page you can find the example usage for java.net URLEncoder encode.

Prototype

public static String encode(String s, Charset charset) 

Source Link

Document

Translates a string into application/x-www-form-urlencoded format using a specific java.nio.charset.Charset Charset .

Usage

From source file:de.mas.telegramircbot.utils.images.ImgurUploader.java

public static String uploadImageAndGetLink(String clientID, byte[] image) throws IOException {
    URL url;//  w w  w  .j a v  a 2  s  .  co m
    url = new URL(Settings.IMGUR_API_URL);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();

    String dataImage = Base64.getEncoder().encodeToString(image);
    String data = URLEncoder.encode("image", "UTF-8") + "=" + URLEncoder.encode(dataImage, "UTF-8");

    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Authorization", "Client-ID " + clientID);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    conn.connect();
    StringBuilder stb = new StringBuilder();
    OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
    wr.write(data);
    wr.flush();

    // Get the response
    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line;
    while ((line = rd.readLine()) != null) {
        stb.append(line).append("\n");
    }
    wr.close();
    rd.close();

    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(ImgurResponse.class, new ImgurResponseDeserializer());
    Gson gson = gsonBuilder.create();

    // The JSON data
    try {
        ImgurResponse response = gson.fromJson(stb.toString(), ImgurResponse.class);
        return response.getLink();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return stb.toString();
}

From source file:edu.cornell.mannlib.semservices.service.impl.UMLSService.java

@Override
public List<Concept> getConcepts(String term) throws Exception {
    List<Concept> conceptList = new ArrayList<Concept>();

    String results = null;//from w w  w  .j a v a2  s  . c o  m
    String dataUrl = submissionUrl + "textToProcess=" + URLEncoder.encode(term, "UTF-8") + "&format=json";

    try {

        StringWriter sw = new StringWriter();
        URL rss = new URL(dataUrl);

        BufferedReader in = new BufferedReader(new InputStreamReader(rss.openStream()));
        String inputLine;
        while ((inputLine = in.readLine()) != null) {
            sw.write(inputLine);
        }
        in.close();

        results = sw.toString();
        //System.out.println("results before processing: "+results);
        conceptList = processOutput(results);
        return conceptList;

    } catch (Exception ex) {
        logger.error("error occurred in servlet", ex);
        return null;
    }
}

From source file:com.salesmanager.core.util.www.integration.fb.SalesManagerFacebookClient.java

static String urlEncode(String string) {
    if (string == null)
        return null;
    try {//  w w  w  .j a v a  2s. c  o  m
        return URLEncoder.encode(string, ENCODING_CHARSET);
    } catch (UnsupportedEncodingException e) {
        throw new IllegalStateException("Platform doesn't support " + ENCODING_CHARSET, e);
    }
}

From source file:org.springframework.ide.eclipse.boot.core.SimpleUriBuilder.java

public void addParameter(String name, String paramValue) {
    try {/*ww w  .  ja  va2  s.  c o m*/
        if (numparams == 0) {
            builder.append("?");
        } else {
            builder.append("&");
        }
        numparams++;

        builder.append(URLEncoder.encode(name, "UTF-8"));
        if (paramValue != null) {
            builder.append("=");
            builder.append(URLEncoder.encode(paramValue, "UTF-8"));
        }
    } catch (Exception e) {
        Log.log(e);
    }
}

From source file:com.linecorp.sample.login.generic.domain.line.LineConfig.java

public String getEncodedRedirectUrl() {
    try {/*  w  w  w  .  j  a  v  a  2  s .c  om*/
        return URLEncoder.encode(redirectUrl, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}

From source file:de.nrw.hbz.regal.sync.ingest.DippDownloader.java

protected void downloadObject(File dir, String pid) {
    try {/*from  ww w  .j a va 2  s.c  om*/
        logger.debug(pid + " start download!");
        URL url = new URL(getServer() + "get/" + pid + "?xml=true");
        File file = new File(dir.getAbsolutePath() + File.separator + URLEncoder.encode(pid, "utf-8") + ".xml");
        String data = null;
        StringWriter writer = new StringWriter();
        IOUtils.copy(url.openStream(), writer);
        data = writer.toString();
        FileUtils.writeStringToFile(file, data, "utf-8");

        downloadStreams(dir, pid);
        downloadConstituent(dir, pid);
        downloadRelatedObject(dir, pid, "rel:hasPart");

        downloadRelatedObject(dir, pid, "rel:isPartOf");
        downloadRelatedObject(new File(getDownloadLocation()), pid, "rel:isMemberOf");
        downloadRelatedObject(new File(getDownloadLocation()), pid, "rel:isSubsetOf");
        downloadRelatedObject(new File(getDownloadLocation()), pid, "rel:isMemberOfCollection");
    } catch (MalformedURLException e) {
        logger.error(e.getMessage());
    } catch (IOException e) {
        logger.error(e.getMessage());
    }

}

From source file:com.xtremelabs.imageutils.DefaultNetworkRequestCreator.java

@Override
public void getInputStream(String url, InputStreamListener listener) {
    HttpEntity entity = null;//from ww w .ja v a  2  s  .  com
    InputStream inputStream = null;

    HttpClient client = new DefaultHttpClient();
    client.getConnectionManager().closeExpiredConnections();
    HttpUriRequest request;
    try {
        request = new HttpGet(url);
    } catch (IllegalArgumentException e) {
        try {
            request = new HttpGet(URLEncoder.encode(url, "UTF-8"));
        } catch (UnsupportedEncodingException e1) {
            String errorMessage = "Unable to download image. Reason: Bad URL. URL: " + url;
            Log.w(ImageLoader.TAG, errorMessage);
            listener.onFailure(errorMessage);
            return;
        }
    }
    HttpResponse response;
    try {
        response = client.execute(request);

        entity = response.getEntity();
        if (entity == null) {
            listener.onFailure("Was unable to retrieve an HttpEntity for the image!");
            return;
        }

        inputStream = new BufferedInputStream(entity.getContent());
        listener.onInputStreamReady(inputStream);
    } catch (IOException e) {
        listener.onFailure("IOException caught when attempting to download an image! Stack trace below. URL: "
                + url + ", Message: " + e.getMessage());
        e.printStackTrace();
    }

    try {
        if (entity != null) {
            entity.consumeContent();
        }
    } catch (IOException e) {
    }

    client.getConnectionManager().closeExpiredConnections();
}

From source file:kmi.taa.core.Crawler.java

public static String[] crawlsaspty(String res, String service, String proxy)
        throws ClientProtocolException, IOException {
    /*//from   w  ww  .  j av  a2s.  c  o m
     *  The String query is the SPARQL query used to get the owl:sameAs subject links
     *  from the knowledge graph where the source triples are from.
     */
    String query = "prefix owl: <http://www.w3.org/2002/07/owl#>" + System.getProperty("line.separator")
            + "select ?obj" + System.getProperty("line.separator") + "where {"
            + System.getProperty("line.separator") + "<" + res + "> owl:sameAs ?obj . "
            + System.getProperty("line.separator") + "}";

    // converting a String to the application/x-www-form-urlencoded MIME format
    String get = service + "?query=" + URLEncoder.encode(query, "utf-8") + "&output=csv";

    SPARQLHTTPClient client = new SPARQLHTTPClient();
    String slinks = client.httpGet(get, proxy);

    /*
     * remove the first line of slinks, i.e., "obj"
     * also removes the double quotes wrapped around uris 
     */
    String[] preformated = slinks.split(System.getProperty("line.separator"));
    String[] formated = new String[preformated.length - 1];
    int j = 0;
    for (int i = 0; i < preformated.length; i++) {
        if (preformated[i].matches("\"http\\S+\"")) {
            formated[j++] = preformated[i].substring(1, preformated[i].length() - 1);
        }
    }

    return formated;

}

From source file:costumetrade.common.sms.SMSActor.java

private void doSend(Sms sms) {

    String ecodingContent = null;
    try {//from   ww w  .  j av a  2  s .co  m
        ecodingContent = URLEncoder.encode(sms.content, StandardCharsets.UTF_8.name());
    } catch (UnsupportedEncodingException ignore) {
    }

    StringBuilder params = new StringBuilder();

    params.append("action=").append(ConfigProperties.getProperty("sms.action")).append("&userid=")
            .append(ConfigProperties.getProperty("sms.userid")).append("&account=")
            .append(ConfigProperties.getProperty("sms.account")).append("&password=")
            .append(ConfigProperties.getProperty("sms.password")).append("&mobile=").append(sms.mobile)
            .append("&content=").append(ecodingContent);

    String xml = sendPostRequestByForm(ConfigProperties.getProperty("sms.url"), params.toString());
    boolean success = isOk(xml);
    if (!success) {
        if (sms.retryCount > 0) {
            scheduler.scheduleOnce(Duration.create(sms.interval, TimeUnit.SECONDS), getSelf(),
                    new Sms(sms.mobile, sms.content, sms.retryCount - 1), dispatcher, ActorRef.noSender());
        }

    }

}

From source file:com.google.android.panoramio.GeoCoderTask.java

public GeoResponse geocode(String address) throws IOException, URISyntaxException, JSONException {

    // prepare a URL to the geocoder
    String url = GEOCODER_REQUEST_PREFIX_FOR_JSON + "?address=" + URLEncoder.encode(address, "UTF-8")
            + "&sensor=false";

    // prepare an HTTP connection to the geocoder
    URI uri = new URI("http", url, null);
    HttpGet get = new HttpGet(uri);

    HttpClient client = new DefaultHttpClient();
    HttpResponse response = client.execute(get);
    HttpEntity entity = response.getEntity();
    String str = Utilities.convertStreamToString(entity.getContent());
    JSONObject json = new JSONObject(str);
    return parse(json);

}