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:ee.ria.xroad.common.util.CertHashBasedOcspResponderClient.java

/**
 * Creates a GET request to the internal cert hash based OCSP responder and expects OCSP responses.
 *
 * @param destination URL of the OCSP response provider
 * @return list of OCSP response objects
 * @throws IOException   if I/O errors occurred
 * @throws OCSPException if the response could not be parsed
 *///from   www .ja v  a  2 s .  c o m
public static List<OCSPResp> getOcspResponsesFromServer(URL destination) throws IOException, OCSPException {
    HttpURLConnection connection = (HttpURLConnection) destination.openConnection();
    connection.setRequestProperty("Accept", MimeTypes.MULTIPART_RELATED);
    connection.setDoOutput(true);
    connection.setConnectTimeout(SystemProperties.getOcspResponderClientConnectTimeout());
    connection.setReadTimeout(SystemProperties.getOcspResponderClientReadTimeout());
    connection.setRequestMethod(METHOD);
    connection.connect();

    if (!VALID_RESPONSE_CODES.contains(connection.getResponseCode())) {
        log.error("Invalid HTTP response ({}) from responder: {}", connection.getResponseCode(),
                connection.getResponseMessage());

        throw new IOException(connection.getResponseMessage());
    }

    MimeConfig config = new MimeConfig.Builder().setHeadlessParsing(connection.getContentType()).build();

    final List<OCSPResp> responses = new ArrayList<>();
    final MimeStreamParser parser = new MimeStreamParser(config);

    parser.setContentHandler(new AbstractContentHandler() {
        @Override
        public void startMultipart(BodyDescriptor bd) {
            parser.setFlat();
        }

        @Override
        public void body(BodyDescriptor bd, InputStream is) throws MimeException, IOException {
            if (bd.getMimeType().equalsIgnoreCase(MimeTypes.OCSP_RESPONSE)) {
                responses.add(new OCSPResp(IOUtils.toByteArray(is)));
            }
        }
    });

    try {
        parser.parse(connection.getInputStream());
    } catch (MimeException e) {
        throw new OCSPException("Error parsing response", e);
    }

    return responses;
}

From source file:Main.java

private static HttpURLConnection _openPostConnection(String purl) throws IOException {
    URL url = new URL(purl);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoInput(true);//w  ww.java 2  s . c  o  m
    connection.setUseCaches(false);
    connection.setDoOutput(true);
    connection.setRequestMethod("GET");
    connection.setRequestProperty("User-Agent", "Android Client Agent");

    return connection;
}

From source file:com.appdynamics.common.RESTClient.java

public static void sendGet(String urlString, String apiKey) {

    try {//ww  w.j  a  va  2 s .  c o m

        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/json");
        conn.setRequestProperty("Authorization",
                "Basic " + new String(Base64.encodeBase64((apiKey).getBytes())));

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

        BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));

        String output;
        logger.info("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            logger.info(output);
        }

        conn.disconnect();

    } catch (MalformedURLException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();

    }

}

From source file:Main.java

public static JSONObject postRequest(String query) {

    HttpURLConnection connection = null;
    try {/*from  w  w w.  java 2s.  c  o m*/
        connection = (HttpURLConnection) new URL(url + query).openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Accept-Charset", charset);

        statusCode = connection.getResponseCode();
        if (statusCode != 200) {
            return null;
        }

        InputStream response = connection.getInputStream();
        BufferedReader bR = new BufferedReader(new InputStreamReader(response));
        String line = "";

        StringBuilder responseStrBuilder = new StringBuilder();
        while ((line = bR.readLine()) != null) {
            responseStrBuilder.append(line);
        }
        response.close();

        return new JSONObject(responseStrBuilder.toString());

    } catch (IOException | JSONException e) {
        e.printStackTrace();
    }
    return new JSONObject();
}

From source file:Main.java

public static void connectAndSendHttp(ByteArrayOutputStream baos) {
    try {//from  w  ww .  j  a v  a2  s .com

        URL url;
        url = new URL("http://10.0.2.2:8080");

        String charset = "UTF-8";

        HttpURLConnection conn;

        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestProperty("Accept-Charset", charset);
        conn.setRequestProperty("ENCTYPE", "multipart/form-data");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);
        OutputStream output = conn.getOutputStream();
        output.write(baos.toByteArray());
        output.close();
        conn.getInputStream();

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

From source file:Main.java

public static JSONObject updateRequest(String query) {
    HttpURLConnection connection = null;
    try {// w  w w  .j a va  2s.c o m
        connection = (HttpURLConnection) new URL(url + query).openConnection();
        connection.setRequestMethod("PUT");
        connection.setRequestProperty("Accept-Charset", charset);

        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
        out.write("Resource content");
        out.close();

        statusCode = connection.getResponseCode();
        if (statusCode != 200) {
            return null;
        }

        InputStream response = connection.getInputStream();
        BufferedReader bR = new BufferedReader(new InputStreamReader(response));
        String line = "";

        StringBuilder responseStrBuilder = new StringBuilder();
        while ((line = bR.readLine()) != null) {
            responseStrBuilder.append(line);
        }
        response.close();
        return new JSONObject(responseStrBuilder.toString());

    } catch (IOException | JSONException e) {
        e.printStackTrace();
    }
    return new JSONObject();
}

From source file:org.elegosproject.romupdater.DownloadManager.java

public static boolean sendAnonymousData() {
    String link = "http://www.elegosproject.org/android/upload.php";
    String data;// w w w . ja v  a2 s .  c om

    SharedData shared = SharedData.getInstance();
    String romName = shared.getRepositoryROMName();
    String romVersion = shared.getDownloadVersion();
    String romPhone = shared.getRepositoryModel();
    String romRepository = shared.getRepositoryUrl();

    if (romName.equals("") || romVersion.equals("") || romPhone.equals("") || romRepository.equals("")) {
        Log.e(TAG, "Internal error - missing system variables.");
        return false;
    }

    if (!checkHttpFile(link))
        return false;
    try {
        data = URLEncoder.encode("phone", "UTF-8") + "=" + URLEncoder.encode(romPhone, "UTF-8");
        data += "&" + URLEncoder.encode("rom_name", "UTF-8") + "=" + URLEncoder.encode(romName, "UTF-8");
        data += "&" + URLEncoder.encode("rom_version", "UTF-8") + "=" + URLEncoder.encode(romVersion, "UTF-8");
        data += "&" + URLEncoder.encode("rom_repository", "UTF-8") + "="
                + URLEncoder.encode(romRepository, "UTF-8");

        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, 3000);

        URL url = new URL(link);
        url.openConnection();
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("User-Agent", "ROMUpdater");
        conn.setDoOutput(true);
        PrintWriter out = new PrintWriter(conn.getOutputStream());
        out.println(data);
        out.close();

        int status = Integer.parseInt(conn.getHeaderField("ROMUpdater-status"));
        if (status == 1)
            return true;

        Log.e(TAG, "It was impossible to send data to the stastistics server ("
                + conn.getHeaderField("ROMUpdater-error") + ").");
        return false;

    } catch (Exception e) {
        Log.e(TAG, "It was impossible to send data to the stastistics server.");
        Log.e(TAG, "Error: " + e.toString());
        return false;
    }
}

From source file:Main.java

public static String getToken(String email, String password) throws IOException {
    // Create the post data
    // Requires a field with the email and the password
    StringBuilder builder = new StringBuilder();
    builder.append("Email=").append(email);
    builder.append("&Passwd=").append(password);
    builder.append("&accountType=GOOGLE");
    builder.append("&source=markson.visuals.sitapp");
    builder.append("&service=ac2dm");

    // Setup the Http Post
    byte[] data = builder.toString().getBytes();
    URL url = new URL("https://www.google.com/accounts/ClientLogin");
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setUseCaches(false);/*from   ww  w .j  a va  2  s  .  c o  m*/
    con.setDoOutput(true);
    con.setRequestMethod("POST");
    con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    con.setRequestProperty("Content-Length", Integer.toString(data.length));

    // Issue the HTTP POST request
    OutputStream output = con.getOutputStream();
    output.write(data);
    output.close();

    // Read the response
    BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String line = null;
    String auth_key = null;
    while ((line = reader.readLine()) != null) {
        if (line.startsWith("Auth=")) {
            auth_key = line.substring(5);
        }
    }

    // Finally get the authentication token
    // To something useful with it
    return auth_key;
}

From source file:GoogleAPI.java

/**
 * Forms an HTTP request, sends it using POST method and returns the result of the request as a JSONObject.
 * /* ww  w  .  j a  va 2  s .  c om*/
 * @param url The URL to query for a JSONObject.
 * @param parameters Additional POST parameters
 * @return The translated String.
 * @throws Exception on error.
 */
protected static JSONObject retrieveJSON(final URL url, final String parameters) throws Exception {
    try {
        final HttpURLConnection uc = (HttpURLConnection) url.openConnection();
        uc.setRequestProperty("referer", referrer);
        uc.setRequestMethod("POST");
        uc.setDoOutput(true);

        final PrintWriter pw = new PrintWriter(uc.getOutputStream());
        pw.write(parameters);
        pw.close();
        uc.getOutputStream().close();

        try {
            final String result = inputStreamToString(uc.getInputStream());

            return new JSONObject(result);
        } finally { // http://java.sun.com/j2se/1.5.0/docs/guide/net/http-keepalive.html
            if (uc.getInputStream() != null) {
                uc.getInputStream().close();
            }
            if (uc.getErrorStream() != null) {
                uc.getErrorStream().close();
            }
            if (pw != null) {
                pw.close();
            }
        }
    } catch (Exception ex) {
        throw new Exception("[google-api-translate-java] Error retrieving translation.", ex);
    }
}

From source file:com.github.thorqin.webapi.oauth2.OAuthClient.java

public static <T> T obtainResource(String authorityServerUri, String accessToken, Class<T> type)
        throws IOException, OAuthException, ClassCastException {
    URL u = new URL(authorityServerUri);
    HttpURLConnection conn = (HttpURLConnection) u.openConnection();
    conn.setRequestProperty("Authorization", "Bearer " + accessToken);
    if (conn.getResponseCode() == 401) {
        String wwwAuth = conn.getHeaderField("WWW-Authenticate");
        if (wwwAuth == null) {
            throw new OAuthException("unauthorized_client");
        } else {//from  ww  w. j  a v  a  2 s  .co  m
            throw new OAuthException(getHeadSubParameter(wwwAuth, "error"),
                    getHeadSubParameter(wwwAuth, "error_description"),
                    getHeadSubParameter(wwwAuth, "error_uri"));
        }
    } else if (conn.getResponseCode() == 400) {
        throw new OAuthException("invalid_request");
    } else if (conn.getResponseCode() > 401 && conn.getResponseCode() < 500) {
        throw new OAuthException("access_denied");
    } else if (conn.getResponseCode() >= 500) {
        throw new OAuthException("server_error");
    } else if (conn.getResponseCode() != 200)
        throw new OAuthException("unsupported_response_type");
    try (InputStream is = conn.getInputStream(); InputStreamReader reader = new InputStreamReader(is)) {
        T resource = Serializer.fromJson(reader, type);
        return resource;
    }
}