Example usage for java.net HttpURLConnection setRequestProperty

List of usage examples for java.net HttpURLConnection setRequestProperty

Introduction

In this page you can find the example usage for java.net HttpURLConnection setRequestProperty.

Prototype

public void setRequestProperty(String key, String value) 

Source Link

Document

Sets the general request property.

Usage

From source file:org.piraso.server.spring.remoting.HttpInvokerRequestExecutorWrapper.java

public RemoteInvocationResult executeRequest(HttpInvokerClientConfiguration config, RemoteInvocation invocation)
        throws Exception {
    if (helper != null && pirasoContext.isMonitored()) {
        try {//from   w  ww  .j  a  v  a 2  s  .c  o  m
            ByteArrayOutputStream baos = helper.getByteArrayOutputStream(invocation);

            HttpURLConnection con = helper.openConnection(config);
            helper.prepareConnection(con, baos.size());
            con.setRequestProperty(REMOTE_ADDRESS_HEADER, pirasoContext.getEntryPoint().getRemoteAddr());
            con.setRequestProperty(REQUEST_ID_HEADER, String.valueOf(pirasoContext.getRequestId()));

            String groupId = getGroupId();
            if (groupId != null) {
                con.setRequestProperty(GROUP_ID_HEADER, groupId);
            }

            helper.writeRequestBody(config, con, baos);
            helper.validateResponse(config, con);
            InputStream responseBody = helper.readResponseBody(config, con);

            return helper.readRemoteInvocationResult(responseBody, config.getCodebaseUrl());
        } catch (HttpInvokerReflectionException e) {
            LOG.warn("Error on propagating piraso context. Will revert to direct delegation.", e);
        }
    }

    return delegate.executeRequest(config, invocation);
}

From source file:com.shuffle.bitcoin.blockchain.BlockchainDotInfo.java

/**
 *
 * This function takes in a transaction hash and passes it to Blockchain.info's API.
 * After some formatting, it returns a bitcoinj Transaction object using this transaction hash.
 *
 *///from ww w .ja  v  a 2  s .  c o  m
public synchronized org.bitcoinj.core.Transaction getTransaction(String transactionHash) throws IOException {

    String url = "https://blockchain.info/tr/rawtx/" + transactionHash + "?format=hex";
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    con.setRequestMethod("GET");
    con.setRequestProperty("User-Agent", userAgent);
    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuilder response = new StringBuilder();
    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    HexBinaryAdapter adapter = new HexBinaryAdapter();
    byte[] bytearray = adapter.unmarshal(response.toString());
    // bitcoinj needs this Context variable
    Context context = Context.getOrCreate(netParams);
    return new org.bitcoinj.core.Transaction(netParams, bytearray);

}

From source file:github.srlee309.lessWrongBookCreator.scraper.PostSectionExtractor.java

/**
 * @param src of image to download and save
 * @param folder to which to save the image
 * @param fileName to use for the saved image
 *///from  ww w. j a va2 s. com
protected final void saveImage(String src, String folder, String fileName) {
    if (fileName.contains("?")) {
        fileName = fileName.substring(0, fileName.lastIndexOf("?"));
    }

    fileName = fileName.replaceAll("[^a-zA-Z0-9.-]", "_"); // replace non valid file fileName characters
    File outputFile = new File(folder + "\\" + fileName);
    try {
        URL url = new URL(src);

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 6.3; rv:36.0) Gecko/20100101 Firefox/36.0");
        connection.setRequestMethod("HEAD");
        connection.setInstanceFollowRedirects(false);
        int rspCode = connection.getResponseCode();
        if (rspCode == 301) { // redirected, so get new url
            String newUrl = connection.getHeaderField("Location");
            url = new URL(newUrl);
        }
        connection.disconnect();
        FileUtils.copyURLToFile(url, outputFile);
    } catch (MalformedURLException e) {
        logger.error("Malformed url exception for image src:  " + src, e);
    } catch (IOException e) {
        logger.error("IO exception for saving image src locally:  " + src, e);
    }
}

From source file:net.ae97.pokebot.extensions.scrolls.PriceCommand.java

@Override
public void runEvent(CommandEvent event) {
    if (event.getArgs().length == 0) {
        event.respond("Usage: .price [name]");
        return;// ww  w  .  ja  va  2 s  .  c o m
    }

    String[] name = event.getArgs();
    try {
        URL playerURL = new URL(url.replace("{name}", StringUtils.join(name, "%20")));
        List<String> lines = new LinkedList<>();
        HttpURLConnection conn = (HttpURLConnection) playerURL.openConnection();
        conn.setRequestProperty("User-Agent", "PokeBot - " + PokeBot.VERSION);
        conn.connect();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                lines.add(line);
            }
        }

        JsonParser parser = new JsonParser();
        JsonElement element = parser.parse(StringUtils.join(lines, "\n"));
        JsonObject obj = element.getAsJsonObject();

        String result = obj.get("msg").getAsString();
        if (!result.equalsIgnoreCase("success")) {
            event.respond("Scroll not found");
            return;
        }
        JsonObject dataObject = obj.get("data").getAsJsonArray().get(0).getAsJsonObject();

        StringBuilder builder = new StringBuilder();

        JsonObject buyObj = dataObject.getAsJsonObject("buy");
        JsonObject sellObj = dataObject.getAsJsonObject("sell");
        JsonObject bmObj = dataObject.getAsJsonObject("bm");

        builder.append("Buy: ").append(buyObj.get("price").getAsInt()).append(" Gold - ");
        builder.append("Sell: ").append(sellObj.get("price").getAsInt()).append(" Gold - ");
        builder.append("Black Market: ").append(bmObj.get("price").getAsInt()).append(" Gold");
        String[] message = builder.toString().split("\n");
        for (String msg : message) {
            event.respond("" + msg);
        }

    } catch (IOException | JsonSyntaxException | IllegalStateException ex) {
        PokeBot.getLogger().log(Level.SEVERE,
                "Error on getting scroll for Scrolls for '" + StringUtils.join(event.getArgs(), " ") + "'", ex);
        event.respond("Error on getting scroll: " + ex.getLocalizedMessage());

    }
}

From source file:com.lmpessoa.sonarview.core.Server.java

private JSONObject readIssuesFromServer(String projectId, int pageIndex)
        throws MalformedURLException, IOException {
    StringBuilder url = new StringBuilder();
    url.append(this.url);
    if (!url.substring(url.length() - 1, url.length()).equals("/")) {
        url.append("/");
    }/*from w w w . j  a va  2  s.  c  o  m*/
    url.append("api/issues/search?componentRoots=");
    url.append(projectId);
    url.append("&resolved=false&pageSize=500");
    if (pageIndex > 1) {
        url.append("&pageIndex=");
        url.append(pageIndex);
    }
    HttpURLConnection con = (HttpURLConnection) new URL(url.toString()).openConnection();
    con.setRequestMethod("GET");
    con.setRequestProperty("User-Agent", "Mozilla/5.0");
    int responseCode = con.getResponseCode();
    if (responseCode != 200) {
        throw new IllegalStateException("Server response code: " + responseCode);
    }
    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer tmp = new StringBuffer();
    while ((inputLine = in.readLine()) != null) {
        tmp.append(inputLine);
    }
    in.close();
    return new JSONObject(tmp.toString());
}

From source file:com.WeatherProxy.java

private void getWeather(String lat, String lng) {
    weatherNow = "";
    String apiUrl = "https://api.forecast.io/forecast/";
    String apiKey = "fad007e59cd36e504fa337d946feb7d2";
    String urlString = apiUrl + apiKey + "/" + lat + "," + lng;

    try {/*from  w ww .jav a2s.c o m*/
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/json");
        conn.connect();

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

        // The body of the response is available as an input stream.
        // Using BufferedReader is good practice for efficient I/O, because it
        // takes lots of little reads and does fewer larger actual I/O
        // operations.  It doesn't make much difference in this case,
        // since we only do one I/O.  But it's still good practice.
        BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
        // api.forecast.io returns a single (very long) line of JSON.
        weatherNow += br.readLine();

    } catch (MalformedURLException e) {
        e.printStackTrace();
        this.weatherNow = "{ 'error': 'MalformedURLException' }";
    } catch (IOException e) {
        e.printStackTrace();
        this.weatherNow = "{ 'error': 'IOException' }";
    }
}

From source file:com.orange.oidc.tim.service.HttpOpenidConnect.java

static String getTimUserInfo(String server_url, String tim_access_token) {
    // android.os.Debug.waitForDebugger();
    // default result
    String result = null;//from ww  w. j ava  2s .  c  o  m

    // check if server is valid
    if (isEmpty(server_url) || isEmpty(tim_access_token)) {
        Logd(TAG, "getTimUserInfo no server url or tim_access_token");
        return null;
    }

    if (!server_url.endsWith("/"))
        server_url += "/";

    // get user info endpoint
    String userinfo_endpoint = getEndpointFromConfigOidc("userinfo_endpoint", server_url);
    if (isEmpty(userinfo_endpoint)) {
        Logd(TAG, "getTimUserInfo : could not get endpoint on server : " + server_url);
        return null;
    }

    // build connection
    HttpURLConnection huc = getHUC(userinfo_endpoint);
    huc.setInstanceFollowRedirects(false);
    huc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    huc.setRequestProperty("Authorization", "Bearer " + tim_access_token);
    Logd("getTimUserInfo", "bearer: " + tim_access_token);

    try {
        // try to establish connection 
        huc.connect();
        // get result
        int responseCode = huc.getResponseCode();
        Logd(TAG, "getTimUserInfo 2 response: " + responseCode);

        // if 200, read http body
        if (responseCode == 200) {
            InputStream is = huc.getInputStream();
            result = convertStreamToString(is);
            is.close();
            Logd(TAG, "getTimUserInfo 2 result: " + result);
        } else {
            // result = "response code: "+responseCode;
        }

        // close connection
        huc.disconnect();

    } catch (Exception e) {
        Log.e(TAG, "getTimUserInfo FAILED");
        e.printStackTrace();
    }

    return result;
}

From source file:lk.appzone.client.MchoiceAventuraSmsSender.java

private void setSdpHeaderParams(HttpURLConnection connection) throws ProtocolException {
    connection.setRequestMethod("POST");
    connection.setRequestProperty("Accept", "text/xml");
    connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
}

From source file:com.microsoft.aad.adal4jsample.AadController.java

private String getUsernamesFromGraph(String accessToken, String tenant) throws Exception {
    URL url = new URL(
            String.format("https://graph.windows.net/%s/users?api-version=2013-04-05", tenant, accessToken));

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    // Set the appropriate header fields in the request header.
    conn.setRequestProperty("api-version", "2013-04-05");
    conn.setRequestProperty("Authorization", accessToken);
    conn.setRequestProperty("Accept", "application/json;odata=minimalmetadata");
    String goodRespStr = HttpClientHelper.getResponseStringFromConn(conn, true);
    // logger.info("goodRespStr ->" + goodRespStr);
    int responseCode = conn.getResponseCode();
    JSONObject response = HttpClientHelper.processGoodRespStr(responseCode, goodRespStr);
    JSONArray users = new JSONArray();

    users = JSONHelper.fetchDirectoryObjectJSONArray(response);

    StringBuilder builder = new StringBuilder();
    User user = null;//from  w w w  .j a  va 2s. c  om
    for (int i = 0; i < users.length(); i++) {
        JSONObject thisUserJSONObject = users.optJSONObject(i);
        user = new User();
        JSONHelper.convertJSONObjectToDirectoryObject(thisUserJSONObject, user);
        builder.append(user.getUserPrincipalName() + "<br/>");
    }
    return builder.toString();
}

From source file:com.jtechme.apphub.net.auth.HttpBasicCredentials.java

@Override
public void authenticate(final HttpURLConnection connection) {

    if (!TextUtils.isEmpty(username) && !TextUtils.isEmpty(password)) {

        // add authorization header from username / password if set
        connection.setRequestProperty("Authorization",
                "Basic " + Base64.encodeBase64String((username + ":" + password).getBytes()));
    }//from   www  . j a  v  a  2  s  . com
}