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:com.orange.oidc.secproxy_service.HttpOpenidConnect.java

static String getUserInfo(String server_url, String access_token) {
    // android.os.Debug.waitForDebugger();

    Log.d(TAG, "getUserInfo server_url=" + server_url);
    Log.d(TAG, "getUserInfo access_token=" + access_token);

    // check if server is valid
    if (isEmpty(server_url) || isEmpty(access_token)) {
        return null;
    }/*from w  ww  .j a  v  a 2  s .co m*/

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

    Logd(TAG, "getUserInfo : " + userinfo_endpoint);
    // build connection
    HttpURLConnection huc = getHUC(userinfo_endpoint + "?access_token=" + access_token);
    huc.setInstanceFollowRedirects(false);
    // huc.setRequestProperty("Content-Type","application/x-www-form-urlencoded");

    huc.setRequestProperty("Authorization", "Bearer " + access_token);

    // default result
    String result = null;

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

        // if 200, read http body
        if (responseCode == 200) {
            InputStream is = huc.getInputStream();
            result = convertStreamToString(is);
            is.close();
        }

        // close connection
        huc.disconnect();

    } catch (Exception e) {
        Logd(TAG, "getUserInfo failed");
        e.printStackTrace();
    }

    return result;
}

From source file:net.couchcontroller.Connection.java

public HttpURLConnection connect(String method) throws Exception {
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    con.setRequestMethod(method);/*from  w  ww . ja  v  a  2s .  c o m*/
    con.setRequestProperty("Accept", "application/json");
    con.setRequestProperty("Content-Type", "application/json");
    authenticate(con);
    return con;
}

From source file:KV78Tester.java

public String[] getLines() throws Exception {
    String uri = "http://openov.nl:5078/line/";
    URL url = new URL(uri);
    HttpURLConnection uc = (HttpURLConnection) url.openConnection();
    uc.setRequestProperty("User-Agent", "KV78Turbo-Test");
    uc.setConnectTimeout(60000);//from  w w w. ja  v a2 s  .c  o m
    uc.setReadTimeout(60000);
    BufferedReader in;
    in = new BufferedReader(new InputStreamReader(uc.getInputStream(), "UTF-8"));
    try {
        return parseLines(in);
    } finally {
        uc.disconnect();
    }
}

From source file:com.apptentive.android.sdk.comm.ApptentiveClient.java

private static ApptentiveHttpResponse performMultipartFilePost(Context context, String oauthToken, String uri,
        String postBody, StoredFile storedFile) {
    Log.d("Performing multipart request to %s", uri);

    ApptentiveHttpResponse ret = new ApptentiveHttpResponse();

    if (storedFile == null) {
        Log.e("StoredFile is null. Unable to send.");
        return ret;
    }/*from www. j ava  2s . co  m*/

    int bytesRead;
    int bufferSize = 4096;
    byte[] buffer;

    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = UUID.randomUUID().toString();

    HttpURLConnection connection;
    DataOutputStream os = null;
    InputStream is = null;

    try {
        is = context.openFileInput(storedFile.getLocalFilePath());

        // Set up the request.
        URL url = new URL(uri);
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);
        connection.setConnectTimeout(DEFAULT_HTTP_CONNECT_TIMEOUT);
        connection.setReadTimeout(DEFAULT_HTTP_SOCKET_TIMEOUT);
        connection.setRequestMethod("POST");

        connection.setRequestProperty("Connection", "Keep-Alive");
        connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
        connection.setRequestProperty("Authorization", "OAuth " + oauthToken);
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("X-API-Version", API_VERSION);
        connection.setRequestProperty("User-Agent", getUserAgentString());

        StringBuilder requestText = new StringBuilder();

        // Write form data
        requestText.append(twoHyphens).append(boundary).append(lineEnd);
        requestText.append("Content-Disposition: form-data; name=\"message\"").append(lineEnd);
        requestText.append("Content-Type: text/plain").append(lineEnd);
        requestText.append(lineEnd);
        requestText.append(postBody);
        requestText.append(lineEnd);

        // Write file attributes.
        requestText.append(twoHyphens).append(boundary).append(lineEnd);
        requestText.append(String.format("Content-Disposition: form-data; name=\"file\"; filename=\"%s\"",
                storedFile.getFileName())).append(lineEnd);
        requestText.append("Content-Type: ").append(storedFile.getMimeType()).append(lineEnd);
        requestText.append(lineEnd);

        Log.d("Post body: " + requestText);

        // Open an output stream.
        os = new DataOutputStream(connection.getOutputStream());

        // Write the text so far.
        os.writeBytes(requestText.toString());

        try {
            // Write the actual file.
            buffer = new byte[bufferSize];
            while ((bytesRead = is.read(buffer, 0, bufferSize)) > 0) {
                os.write(buffer, 0, bytesRead);
            }
        } catch (IOException e) {
            Log.d("Error writing file bytes to HTTP connection.", e);
            ret.setBadPayload(true);
            throw e;
        }

        os.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
        os.close();

        ret.setCode(connection.getResponseCode());
        ret.setReason(connection.getResponseMessage());

        // TODO: These streams may not be ready to read now. Put this in a new thread.
        // Read the normal response.
        InputStream nis = null;
        ByteArrayOutputStream nbaos = null;
        try {
            Log.d("Sending file: " + storedFile.getLocalFilePath());
            nis = connection.getInputStream();
            nbaos = new ByteArrayOutputStream();
            byte[] eBuf = new byte[1024];
            int eRead;
            while (nis != null && (eRead = nis.read(eBuf, 0, 1024)) > 0) {
                nbaos.write(eBuf, 0, eRead);
            }
            ret.setContent(nbaos.toString());
        } catch (IOException e) {
            Log.w("Can't read return stream.", e);
        } finally {
            Util.ensureClosed(nis);
            Util.ensureClosed(nbaos);
        }

        // Read the error response.
        InputStream eis = null;
        ByteArrayOutputStream ebaos = null;
        try {
            eis = connection.getErrorStream();
            ebaos = new ByteArrayOutputStream();
            byte[] eBuf = new byte[1024];
            int eRead;
            while (eis != null && (eRead = eis.read(eBuf, 0, 1024)) > 0) {
                ebaos.write(eBuf, 0, eRead);
            }
            if (ebaos.size() > 0) {
                ret.setContent(ebaos.toString());
            }
        } catch (IOException e) {
            Log.w("Can't read error stream.", e);
        } finally {
            Util.ensureClosed(eis);
            Util.ensureClosed(ebaos);
        }

        Log.d("HTTP " + connection.getResponseCode() + ": " + connection.getResponseMessage() + "");
        Log.v(ret.getContent());
    } catch (FileNotFoundException e) {
        Log.e("Error getting file to upload.", e);
    } catch (MalformedURLException e) {
        Log.e("Error constructing url for file upload.", e);
    } catch (SocketTimeoutException e) {
        Log.w("Timeout communicating with server.");
    } catch (IOException e) {
        Log.e("Error executing file upload.", e);
    } finally {
        Util.ensureClosed(is);
        Util.ensureClosed(os);
    }
    return ret;
}

From source file:org.csware.ee.utils.Tools.java

/**
 * ??byte//  w  w w.j a v a  2s .c  o  m
 * @param path 
 * @return  byte[]
 * @throws Exception
 */
public static byte[] getByteArray(String path) {
    try {
        String boundary = "*****";
        //            System.setProperty("http.keepAlive", "false");
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(6000);
        conn.setReadTimeout(6000);
        conn.setRequestMethod("GET");
        conn.setRequestProperty("connection", "Keep-Alive");
        //            conn.setRequestProperty("Content-Type",
        //                    "multipart/form-data;boundary=" + boundary);
        conn.setRequestProperty("Accept-Encoding", "gzip,deflate,sdch");
        //            conn.setRequestProperty("Cache-Control", "max-age=0");
        conn.setRequestProperty("Content-Type", "text/html;charset=UTF-8");
        //            conn.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8");
        //            conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
        //            conn.setRequestProperty("Host", "pbank.95559.com.cn");
        //            conn.setRequestProperty("Origin", "https://creditcardapp.bankcomm.com");
        //            conn.setRequestProperty("Referer", "https://pbank.95559.com.cn/personbank/credit/pb0525_apply_result_qry_req.jsp");
        conn.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.114 Safari/537.36");

        if (conn.getResponseCode() == 200) {
            InputStream inputStream = conn.getInputStream();
            return streamToByte(inputStream);
        }
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
    return null;
}

From source file:com.vaadin.tests.requesthandlers.UnsupportedBrowserHandlerUserAgents.java

private String requestWithUserAgent(String userAgent) {
    try {/*w  ww .j  ava  2s .c o m*/
        String url = "http://" + PrivateTB3Configuration.getConfiguredDeploymentHostname() + ":"
                + PrivateTB3Configuration.getConfiguredDeploymentPort() + "/run/"
                + com.vaadin.tests.components.ui.UIInitTest.class.getName() + "/";

        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setRequestProperty("User-Agent", userAgent);

        String response = IOUtils.toString(connection.getInputStream());
        connection.disconnect();

        return response;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

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

@Override
public void runEvent(CommandEvent event) {
    try {//from  w ww  .  jav a  2  s  .c o m
        List<String> lines = new LinkedList<>();
        HttpURLConnection conn = (HttpURLConnection) new URL(url).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();
        int online = obj.get("data").getAsJsonObject().get("online").getAsInt();
        event.respond("there are " + online + " online users in Scrolls");
    } catch (IOException | JsonSyntaxException ex) {
        PokeBot.getLogger().log(Level.SEVERE, "Error on getting online players for Scrolls", ex);
        event.respond("error on finding online players: " + ex.getLocalizedMessage());
    }
}

From source file:com.orange.oidc.secproxy_service.HttpOpenidConnect.java

public static boolean logout(String server_url) {

    if (isEmpty(server_url)) {
        Logd(TAG, "revokSite no server url");
        return false;
    }/*  www .j  a  v a 2  s  .  c  o  m*/

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

    // get end session endpoint
    String end_session_endpoint = getEndpointFromConfigOidc("end_session_endpoint", server_url);
    if (isEmpty(end_session_endpoint)) {
        Logd(TAG, "logout : could not get end_session_endpoint on server : " + server_url);
        return false;
    }

    // set up connection
    HttpURLConnection huc = getHUC(end_session_endpoint);

    // TAZTAG test
    // huc.setInstanceFollowRedirects(false);
    huc.setInstanceFollowRedirects(true);
    // result : follows redirection is ok for taztag

    huc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    huc.setDoOutput(true);
    huc.setChunkedStreamingMode(0);
    // prepare parameters
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);

    try {
        // write parameters to http connection
        OutputStream os = huc.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        // get URL encoded string from list of key value pairs
        String postParam = getQuery(nameValuePairs);
        Logd("Logout", "url: " + end_session_endpoint);
        Logd("Logout", "POST: " + postParam);
        writer.write(postParam);
        writer.flush();
        writer.close();
        os.close();

        // try to connect
        huc.connect();
        // connexion status
        int responseCode = huc.getResponseCode();
        Logd(TAG, "Logout response: " + responseCode);
        // if 200 - OK
        if (responseCode == 200) {
            return true;
        }
        huc.disconnect();
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }

    return false;
}

From source file:data.GoogleBooksWS.java

@Override
public void setDataType(HttpURLConnection conn) {
    conn.setRequestProperty("Accept", "application/json");
}

From source file:KV78Tester.java

public void checkLines(String[] lines) throws IOException {
    System.out.println("Checking " + lines.length + " lines");
    for (int i = 0; i < lines.length; i++) {
        String uri = "http://openov.nl:5078/line/" + lines[i];
        URL url = new URL(uri);
        HttpURLConnection uc = (HttpURLConnection) url.openConnection();
        uc.setRequestProperty("User-Agent", "KV78Turbo-Test");
        uc.setConnectTimeout(60000);/*from ww  w  .j  av  a 2  s.com*/
        uc.setReadTimeout(60000);
        BufferedReader in;
        in = new BufferedReader(new InputStreamReader(uc.getInputStream(), "UTF-8"));
        try {
            checkLines(in);
        } finally {
            uc.disconnect();
        }
    }
}