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:net.maxgigapop.mrs.driver.openstack.OpenStackRESTClient.java

private static String sendGET(URL url, HttpURLConnection con, String userAgent, String tokenId)
        throws IOException {

    con.setRequestMethod("GET");
    con.setRequestProperty("User-Agent", userAgent);
    con.setRequestProperty("X-Auth-Token", tokenId);

    logger.log(Level.INFO, "Sending GET request to URL : {0}", url);
    int responseCode = con.getResponseCode();
    logger.log(Level.INFO, "Response Code : {0}", responseCode);

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;/*www.j av  a 2 s. c o  m*/
    StringBuilder responseStr = new StringBuilder();

    while ((inputLine = in.readLine()) != null) {
        responseStr.append(inputLine);
    }
    in.close();

    return responseStr.toString();
}

From source file:com.futureplatforms.kirin.internal.attic.IOUtils.java

public static InputStream postConnection(Context context, URL url, String method, String urlParameters)
        throws IOException {
    if (!url.getProtocol().startsWith("http")) {
        return url.openStream();
    }/*from  w  ww. ja  v  a 2 s.c o  m*/

    URLConnection c = url.openConnection();

    HttpURLConnection connection = (HttpURLConnection) c;

    connection.setRequestMethod(method.toUpperCase());
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
    connection.setRequestProperty("Content-Language", "en-US");

    connection.setUseCaches(false);
    connection.setDoInput(true);
    connection.setDoOutput(true);

    OutputStream output = null;
    try {
        output = connection.getOutputStream();
        output.write(urlParameters.getBytes("UTF-8"));
        output.flush();
    } finally {
        IOUtils.close(output);
    }
    return connection.getInputStream();
}

From source file:ai.eve.volley.stack.HurlStack.java

private static void addBodyIfExists(HttpURLConnection connection, Request<?> request)
        throws IOException, AuthFailureError {
    connection.setDoOutput(true);//  w  ww  .  ja v  a 2s  . c o m
    connection.setRequestProperty("connection", "Keep-Alive");
    connection.addRequestProperty(HTTP.CONTENT_TYPE, request.getBodyContentType());
    request.getBody(connection);
}

From source file:hudson.Main.java

/**
 * Run command and send result to {@code ExternalJob} in the {@code external-monitor-job} plugin.
 * Obsoleted by {@code SetExternalBuildResultCommand} but kept here for compatibility.
 *///from w  ww  .j  a v a 2 s. c om
public static int remotePost(String[] args) throws Exception {
    String projectName = args[0];

    String home = getHudsonHome();
    if (!home.endsWith("/"))
        home = home + '/'; // make sure it ends with '/'

    // check for authentication info
    String auth = new URL(home).getUserInfo();
    if (auth != null)
        auth = "Basic " + new Base64Encoder().encode(auth.getBytes("UTF-8"));

    {// check if the home is set correctly
        HttpURLConnection con = open(new URL(home));
        if (auth != null)
            con.setRequestProperty("Authorization", auth);
        con.connect();
        if (con.getResponseCode() != 200 || con.getHeaderField("X-Hudson") == null) {
            System.err.println(home + " is not Hudson (" + con.getResponseMessage() + ")");
            return -1;
        }
    }

    URL jobURL = new URL(home + "job/" + Util.encode(projectName).replace("/", "/job/") + "/");

    {// check if the job name is correct
        HttpURLConnection con = open(new URL(jobURL, "acceptBuildResult"));
        if (auth != null)
            con.setRequestProperty("Authorization", auth);
        con.connect();
        if (con.getResponseCode() != 200) {
            System.err.println(jobURL + " is not a valid external job (" + con.getResponseCode() + " "
                    + con.getResponseMessage() + ")");
            return -1;
        }
    }

    // get a crumb to pass the csrf check
    String crumbField = null, crumbValue = null;
    try {
        HttpURLConnection con = open(
                new URL(home + "crumbIssuer/api/xml?xpath=concat(//crumbRequestField,\":\",//crumb)'"));
        if (auth != null)
            con.setRequestProperty("Authorization", auth);
        String line = IOUtils.readFirstLine(con.getInputStream(), "UTF-8");
        String[] components = line.split(":");
        if (components.length == 2) {
            crumbField = components[0];
            crumbValue = components[1];
        }
    } catch (IOException e) {
        // presumably this Hudson doesn't use CSRF protection
    }

    // write the output to a temporary file first.
    File tmpFile = File.createTempFile("jenkins", "log");
    try {
        int ret;
        try (OutputStream os = Files.newOutputStream(tmpFile.toPath());
                Writer w = new OutputStreamWriter(os, "UTF-8")) {
            w.write("<?xml version='1.1' encoding='UTF-8'?>");
            w.write("<run><log encoding='hexBinary' content-encoding='" + Charset.defaultCharset().name()
                    + "'>");
            w.flush();

            // run the command
            long start = System.currentTimeMillis();

            List<String> cmd = new ArrayList<String>();
            for (int i = 1; i < args.length; i++)
                cmd.add(args[i]);
            Proc proc = new Proc.LocalProc(cmd.toArray(new String[0]), (String[]) null, System.in,
                    new DualOutputStream(System.out, new EncodingStream(os)));

            ret = proc.join();

            w.write("</log><result>" + ret + "</result><duration>" + (System.currentTimeMillis() - start)
                    + "</duration></run>");
        } catch (InvalidPathException e) {
            throw new IOException(e);
        }

        URL location = new URL(jobURL, "postBuildResult");
        while (true) {
            try {
                // start a remote connection
                HttpURLConnection con = open(location);
                if (auth != null)
                    con.setRequestProperty("Authorization", auth);
                if (crumbField != null && crumbValue != null) {
                    con.setRequestProperty(crumbField, crumbValue);
                }
                con.setDoOutput(true);
                // this tells HttpURLConnection not to buffer the whole thing
                con.setFixedLengthStreamingMode((int) tmpFile.length());
                con.connect();
                // send the data
                try (InputStream in = Files.newInputStream(tmpFile.toPath())) {
                    org.apache.commons.io.IOUtils.copy(in, con.getOutputStream());
                } catch (InvalidPathException e) {
                    throw new IOException(e);
                }

                if (con.getResponseCode() != 200) {
                    org.apache.commons.io.IOUtils.copy(con.getErrorStream(), System.err);
                }

                return ret;
            } catch (HttpRetryException e) {
                if (e.getLocation() != null) {
                    // retry with the new location
                    location = new URL(e.getLocation());
                    continue;
                }
                // otherwise failed for reasons beyond us.
                throw e;
            }
        }
    } finally {
        tmpFile.delete();
    }
}

From source file:com.mycompany.craftdemo.utility.java

public static JSONObject getAPIData(String apiURL) {
    try {//  w  ww. j a v a2s  . c om
        URL url = new URL(apiURL);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/json");

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

        BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
        StringBuilder sb = new StringBuilder();
        String output;
        while ((output = br.readLine()) != null)
            sb.append(output);

        String res = sb.toString();
        JSONParser parser = new JSONParser();
        JSONObject json = null;
        try {
            json = (JSONObject) parser.parse(res);
        } catch (ParseException ex) {
            ex.printStackTrace();
        }
        //resturn api data in json format
        return json;

    } catch (MalformedURLException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();

    }
    return null;
}

From source file:connector.ISConnector.java

public static JSONObject processRequest(String servlet, byte[] query) {
    JSONObject response = null;/*from w  w w .  ja v  a2 s  . c o m*/
    if (servlet != null && !servlet.startsWith("/"))
        servlet = "/" + servlet;
    try {
        // Establish HTTP connection with Identity Service
        URL url = new URL(CONTEXT_PATH + servlet);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setAllowUserInteraction(false);
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        //Create the form content
        try (OutputStream out = conn.getOutputStream()) {
            out.write(query);
            out.close();
        }

        // Buffer the result into a string
        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = rd.readLine()) != null) {
            sb.append(line);
        }

        rd.close();
        conn.disconnect();
        response = (JSONObject) new JSONParser().parse(sb.toString());

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

    return response;
}

From source file:Main.IrcBot.java

public static void postRequest(String pasteCode, PrintWriter out) {
    try {//from   w w w.j a v  a 2s  . c o m
        String url = "http://pastebin.com/raw.php?i=" + pasteCode;
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        //add reuqest header
        con.setRequestMethod("POST");
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

        String urlParameters = "";

        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + url);
        System.out.println("Post parameters : " + urlParameters);
        System.out.println("Response Code : " + responseCode);

        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine + "\n");
        }
        in.close();

        //print result
        System.out.println(response.toString());

        if (response.length() > 0) {
            IrcBot.postGit(response.toString(), out);
        } else {
            out.println("PRIVMSG #learnprogramming :The PasteBin URL is not valid.");
        }
    } catch (Exception p) {

    }
}

From source file:circleplus.app.http.AbstractHttpApi.java

private static HttpURLConnection getHttpURLConnection(URL url, int requestMethod, boolean acceptJson)
        throws IOException {
    if (D)//from  w  w  w . j  ava 2s. c  o  m
        Log.d(TAG, "execute method: " + requestMethod + " url: " + url.toString() + " accept JSON ?= "
                + acceptJson);

    String method;
    boolean isPost;
    switch (requestMethod) {
    case REQUEST_METHOD_GET:
        method = "GET";
        isPost = false;
        break;
    case REQUEST_METHOD_POST:
        method = "POST";
        isPost = true;
        break;
    default:
        method = "GET";
        isPost = false;
        break;
    }

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setReadTimeout(TIMEOUT);
    conn.setConnectTimeout(TIMEOUT);
    conn.setRequestProperty("Content-Type", JSON_UTF8_CONTENT_TYPE);
    if (isPost && acceptJson) {
        conn.setRequestProperty("Accept", JSON_CONTENT_TYPE);
    }
    conn.setRequestMethod(method);
    /* setDoOutput(true) equals setRequestMethod("POST") */
    conn.setDoOutput(isPost);
    conn.setChunkedStreamingMode(0);
    // Starts the query
    conn.connect();

    return conn;
}

From source file:au.com.tyo.sn.shortener.GooGl.java

private static String post(String url) {
    HttpURLConnection httpcon = null;

    try {//from  w ww . jav  a  2  s . c  o m
        httpcon = (HttpURLConnection) ((new URL(GOO_GL_REQUEST_URL).openConnection()));

        httpcon.setDoOutput(true);
        httpcon.setRequestProperty("Content-Type", "application/json");
        httpcon.setRequestProperty("Accept", "application/json");
        httpcon.setRequestMethod("POST");
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    byte[] outputBytes = { 0 };
    OutputStream os = null;
    InputStream is = null;
    BufferedReader in = null;
    StringBuilder text = new StringBuilder();

    try {
        outputBytes = ("{'longUrl': \"" + url + "\"}").getBytes("UTF-8");
        httpcon.setRequestProperty("Content-Length", Integer.toString(outputBytes.length));
        httpcon.connect();
        os = httpcon.getOutputStream();
        os.write(outputBytes);
        is = httpcon.getInputStream();
        in = new BufferedReader(new InputStreamReader(is, "UTF-8"));

        if (in != null) {
            // get page text
            String line;

            while ((line = in.readLine()) != null) {
                text.append(line);
                text.append("\n");
            }
        }

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

    return text.toString();
}

From source file:com.evrythng.java.wrapper.util.FileUtils.java

private static HttpURLConnection getConnectionForPublicUpload(final URL url, final String contentType)
        throws IOException {

    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod(HttpPut.METHOD_NAME);
    connection.setRequestProperty(HttpHeaders.CONTENT_TYPE, contentType);
    connection.setRequestProperty(X_AMZ_ACL_HEADER_NAME, X_AMZ_ACL_HEADER_VALUE_PUBLIC_READ);
    connection.setDoOutput(true);/*from ww  w  . j a  va  2s  . c  om*/
    connection.connect();
    return connection;
}