Example usage for java.net HttpURLConnection addRequestProperty

List of usage examples for java.net HttpURLConnection addRequestProperty

Introduction

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

Prototype

public void addRequestProperty(String key, String value) 

Source Link

Document

Adds a general request property specified by a key-value pair.

Usage

From source file:vc.fq.FanfouExporter.ExportTread.java

/**
 *  GET /statuses/user_timeline ????/*from   ww w  .j a v a  2s . c om*/
 * @param pageID ?
 * @param userID ID
 * @return
 * @see https://github.com/FanfouAPI/FanFouAPIDoc/wiki/statuses.user-timeline
 */
public HttpURLConnection timeline(int page, String userID) {
    long timestamp = System.currentTimeMillis() / 1000;
    long nonce = System.nanoTime();
    String strURL = "http://api.fanfou.com/statuses/user_timeline.json";
    String pageID = String.valueOf(page);

    StringBuffer strBuf = new StringBuffer(200);
    strBuf.append("count=60");
    if (userID != null) {
        strBuf.append("&id=").append(userID);
    }
    strBuf.append("&oauth_consumer_key=").append(consumer_key);
    strBuf.append("&oauth_nonce=").append(nonce);
    strBuf.append("&oauth_signature_method=HMAC-SHA1");
    strBuf.append("&oauth_timestamp=").append(timestamp);
    strBuf.append("&oauth_token=").append(oauth_token);
    String params = strBuf.toString();

    params = params + "&page=" + pageID;

    try {
        params = "GET&" + URLEncoder.encode(strURL, "UTF-8") + "&" + URLEncoder.encode(params, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        setLog("?");
    }
    String sig = generateSignature(params, oauth_token_secret);

    strBuf = new StringBuffer(280);
    strBuf.append("OAuth realm=\"Fantalker\",oauth_consumer_key=\"");
    strBuf.append(consumer_key);
    strBuf.append("\",oauth_signature_method=\"HMAC-SHA1\"");
    strBuf.append(",oauth_timestamp=\"").append(timestamp).append("\"");
    strBuf.append(",oauth_nonce=\"").append(nonce).append("\"");
    strBuf.append(",oauth_signature=\"").append(sig).append("\"");
    strBuf.append(",oauth_token=\"").append(oauth_token).append("\"");
    String authorization = strBuf.toString();

    strURL = strURL + "?count=60&page=" + pageID;
    if (userID != null) {
        strURL = strURL + "&id=" + userID;
    }
    try {
        URL url = new URL(strURL);
        HttpURLConnection connection;
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.addRequestProperty("Authorization", authorization);
        connection.connect();
        return connection;
    } catch (SocketTimeoutException e) {
        setLog(" " + e.getMessage());
    } catch (IOException e) {
        setLog(e.getMessage());
    }
    return null;
}

From source file:org.alfresco.repo.web.scripts.activities.SiteActivitySystemTest.java

private String callOutWebScript(String urlString, String method, String ticket)
        throws MalformedURLException, URISyntaxException, IOException {
    URL url = new URL(urlString);

    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod(method);/*from   w  w w . j a v a  2 s . c  o  m*/

    if (ticket != null) {
        // add Base64 encoded authorization header
        // refer to: http://wiki.alfresco.com/wiki/Web_Scripts_Framework#HTTP_Basic_Authentication
        conn.addRequestProperty("Authorization", "Basic " + Base64.encodeBytes(ticket.getBytes()));
    }

    String result = null;
    InputStream is = null;
    BufferedReader br = null;

    try {
        is = conn.getInputStream();
        br = new BufferedReader(new InputStreamReader(is));

        String line = null;
        StringBuffer sb = new StringBuffer();
        while (((line = br.readLine()) != null)) {
            sb.append(line);
        }

        result = sb.toString();
    } finally {
        if (br != null) {
            br.close();
        }
        ;
        if (is != null) {
            is.close();
        }
        ;
    }

    return result;
}

From source file:com.castlemock.web.mock.rest.web.rest.controller.AbstractRestServiceController.java

/**
 * The method provides the functionality to forward a request to another endpoint
 * @param restRequest The incoming request
 * @param restMethod The REST method which the incoming request belongs to
 * @return The response received from the external endpoint
 *///from  w w w  . j a  v  a  2 s  .c  o m
protected RestResponseDto forwardRequest(final RestRequestDto restRequest, final String projectId,
        final String applicationId, final String resourceId, final RestMethodDto restMethod) {
    if (demoMode) {
        // If the application is configured to run in demo mode, then use mocked response instead
        return mockResponse(restRequest, projectId, applicationId, resourceId, restMethod);
    }

    final RestResponseDto response = new RestResponseDto();
    HttpURLConnection connection = null;
    OutputStream outputStream = null;
    BufferedReader bufferedReader = null;
    try {
        final String parameterUri = HttpMessageSupport.buildParameterUri(restRequest.getHttpParameters());
        final URL url = new URL(restMethod.getForwardedEndpoint() + restRequest.getUri() + parameterUri);
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod(restRequest.getHttpMethod().name());
        for (HttpHeaderDto httpHeader : restRequest.getHttpHeaders()) {
            connection.addRequestProperty(httpHeader.getName(), httpHeader.getValue());
        }

        if (HttpMethod.POST.equals(restRequest.getHttpMethod())
                || HttpMethod.PUT.equals(restRequest.getHttpMethod())
                || HttpMethod.DELETE.equals(restRequest.getHttpMethod())) {
            outputStream = connection.getOutputStream();
            outputStream.write(restRequest.getBody().getBytes());
            outputStream.flush();
        }

        InputStreamReader inputStreamReader = null;
        if (connection.getResponseCode() == OK_RESPONSE) {
            inputStreamReader = new InputStreamReader(connection.getInputStream());
        } else {
            inputStreamReader = new InputStreamReader(connection.getErrorStream());
        }

        bufferedReader = new BufferedReader(inputStreamReader);

        final StringBuilder stringBuilder = new StringBuilder();
        String buffer;
        while ((buffer = bufferedReader.readLine()) != null) {
            stringBuilder.append(buffer);
            stringBuilder.append(NEW_LINE);
        }

        final List<HttpHeaderDto> responseHttpHeaders = HttpMessageSupport.extractHttpHeaders(connection);
        response.setBody(stringBuilder.toString());
        response.setMockResponseName(FORWARDED_RESPONSE_NAME);
        response.setHttpHeaders(responseHttpHeaders);
        response.setHttpStatusCode(connection.getResponseCode());
        return response;
    } catch (IOException exception) {
        LOGGER.error("Unable to forward request", exception);
        throw new RestException("Unable to forward request to configured endpoint");
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException exception) {
                LOGGER.error("Unable to close output stream", exception);
            }
        }
        if (bufferedReader != null) {
            try {
                bufferedReader.close();
            } catch (IOException exception) {
                LOGGER.error("Unable to close buffered reader", exception);
            }
        }
    }
}

From source file:org.runnerup.export.EndomondoSynchronizer.java

@Override
public Status connect() {
    if (isConfigured()) {
        return Status.OK;
    }//from w  w  w.j  a v a2  s  .  c om

    Status s = Status.NEED_AUTH;
    s.authMethod = Synchronizer.AuthMethod.USER_PASS;
    if (username == null || password == null) {
        return s;
    }

    /**
     * Generate deviceId
     */
    deviceId = UUID.randomUUID().toString();

    Exception ex = null;
    HttpURLConnection conn = null;
    logout();
    try {

        /**
        *
        */
        String login = AUTH_URL;
        FormValues kv = new FormValues();
        kv.put("email", username);
        kv.put("password", password);
        kv.put("v", "2.4");
        kv.put("action", "pair");
        kv.put("deviceId", deviceId);
        kv.put("country", "N/A");

        conn = (HttpURLConnection) new URL(login).openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod(RequestMethod.POST.name());
        conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        OutputStream wr = new BufferedOutputStream(conn.getOutputStream());
        kv.write(wr);
        wr.flush();
        wr.close();

        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        JSONObject res = parseKVP(in);
        conn.disconnect();

        int responseCode = conn.getResponseCode();
        String amsg = conn.getResponseMessage();
        if (responseCode == HttpStatus.SC_OK && "OK".contentEquals(res.getString("_0"))
                && res.has("authToken")) {
            authToken = res.getString("authToken");
            return Status.OK;
        }
        Log.e(getName(), "FAIL: code: " + responseCode + ", msg=" + amsg + ", res=" + res.toString());
        return s;
    } catch (MalformedURLException e) {
        ex = e;
    } catch (IOException e) {
        ex = e;
    } catch (JSONException e) {
        ex = e;
    }

    if (conn != null)
        conn.disconnect();

    s = Synchronizer.Status.ERROR;
    s.ex = ex;
    if (ex != null) {
        ex.printStackTrace();
    }
    return s;
}

From source file:vc.fq.FanfouExporter.ExportTread.java

/**
 * ?XAuth//from   w  ww. j a v  a 2s  .c o m
 * @param username
 * @param password
 * @return oauth_token=Access_Token&oauth_token_secret=Access_Token_Secret
 */
public String XAuth(String username, String password) {
    URL url;
    try {
        url = new URL("http://fanfou.com/oauth/access_token");
    } catch (MalformedURLException e) {
        setLog(e.getMessage());
        return null;
    }
    long timestamp = System.currentTimeMillis() / 1000;
    long nonce = System.nanoTime();
    String params;
    String authorization;
    params = "oauth_consumer_key=" + consumer_key + "&oauth_nonce=" + String.valueOf(nonce)
            + "&oauth_signature_method=HMAC-SHA1" + "&oauth_timestamp=" + String.valueOf(timestamp)
            + "&x_auth_username=" + username + "&x_auth_password=" + password + "&x_auth_mode=client_auth";

    try {
        params = "GET&" + URLEncoder.encode(url.toString(), "UTF-8") + "&" + URLEncoder.encode(params, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        setLog("?");
    }

    String sig = generateSignature(params);

    authorization = "OAuth realm=\"Fantalker\",oauth_consumer_key=\"" + consumer_key
            + "\",oauth_signature_method=\"HMAC-SHA1\"" + ",oauth_timestamp=\"" + String.valueOf(timestamp)
            + "\"" + ",oauth_nonce=\"" + String.valueOf(nonce) + "\"" + ",oauth_signature=\"" + sig + "\""
            + ",x_auth_username=\"" + username + "\"" + ",x_auth_password=\"" + password + "\""
            + ",x_auth_mode=\"client_auth\"";

    try {
        HttpURLConnection connection;
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.addRequestProperty("Authorization", authorization);
        connection.connect();

        String line;
        if (connection.getResponseCode() == 200) {

        } else if (connection.getResponseCode() == 401) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
            String log = Main.txtLog.getText();
            line = reader.readLine();
            while (line != null) {
                log = log + "\r\n" + line;
                line = reader.readLine();
            }
            Main.txtLog.setText(log);
            JOptionPane.showMessageDialog(null, "id?", "", JOptionPane.ERROR_MESSAGE);
            return null;
        } else {
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
            String log = Main.txtLog.getText();
            line = reader.readLine();
            while (line != null) {
                log = log + "\r\n" + line;
                line = reader.readLine();
            }
            setLog(log);
            JOptionPane.showMessageDialog(null, "?", "",
                    JOptionPane.ERROR_MESSAGE);
            return null;
        }
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        line = reader.readLine();
        return line;
    } catch (SocketTimeoutException e) {
        setLog("?:" + e.getMessage());
        return null;
    } catch (IOException e) {
        setLog("?? I/O:" + e.getMessage());
        return null;
    }
}

From source file:export.GarminUploader.java

private Status connectNew() throws MalformedURLException, IOException, JSONException {
    Status s = Status.NEED_AUTH;/*from   w w  w . j ava2  s .c  o m*/
    s.authMethod = Uploader.AuthMethod.USER_PASS;

    FormValues fv = new FormValues();
    fv.put("service", "http://connect.garmin.com/post-auth/login");
    fv.put("clientId", "GarminConnect");
    fv.put("consumeServiceTicket", "false");

    HttpURLConnection conn = get("https://sso.garmin.com/sso/login", fv);
    addCookies(conn);
    expectResponse(conn, 200, "Connection 1: ");
    getCookies(conn);
    getFormValues(conn);
    conn.disconnect();

    // try again
    FormValues data = new FormValues();
    data.put("username", username);
    data.put("password", password);
    data.put("_eventId", "submit");
    data.put("embed", "true");
    data.put("lt", formValues.get("lt"));

    conn = post("https://sso.garmin.com/sso/login", fv);
    conn.setInstanceFollowRedirects(false);
    conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    addCookies(conn);
    postData(conn, data);
    expectResponse(conn, 200, "Connection 2: ");
    getCookies(conn);
    String html = getFormValues(conn);
    conn.disconnect();

    /* this is really horrible */
    int start = html.indexOf("?ticket=");
    if (start == -1) {
        throw new IOException("Invalid login, unable to locate ticket");
    }
    start += "?ticket=".length();
    int end = html.indexOf("'", start);
    String ticket = html.substring(start, end);

    // connection 3...
    fv.clear();
    fv.put("ticket", ticket);

    conn = get("http://connect.garmin.com/post-auth/login", fv);
    conn.setInstanceFollowRedirects(false);
    addCookies(conn);
    expectResponse(conn, 302, "Connection 3: ");
    List<String> fields = conn.getHeaderFields().get("location");
    getCookies(conn);

    // connection 4...
    conn = get(fields.get(0), null);
    conn.setInstanceFollowRedirects(false);
    addCookies(conn);
    expectResponse(conn, 302, "Connection 4: ");
    getCookies(conn);
    conn.disconnect();
    return checkLogin();
}

From source file:org.runnerup.export.GarminUploader.java

private Status connectNew() throws MalformedURLException, IOException, JSONException {
    Status s = Status.NEED_AUTH;//www.  j  ava2  s. c  o  m
    s.authMethod = Uploader.AuthMethod.USER_PASS;

    FormValues fv = new FormValues();
    fv.put("service", "https://connect.garmin.com/post-auth/login");
    fv.put("clientId", "GarminConnect");
    fv.put("consumeServiceTicket", "false");

    HttpURLConnection conn = get("https://sso.garmin.com/sso/login", fv);
    addCookies(conn);
    expectResponse(conn, 200, "Connection 1: ");
    getCookies(conn);
    getFormValues(conn);
    conn.disconnect();

    // try again
    FormValues data = new FormValues();
    data.put("username", username);
    data.put("password", password);
    data.put("_eventId", "submit");
    data.put("embed", "true");
    data.put("lt", formValues.get("lt"));

    conn = post("https://sso.garmin.com/sso/login", fv);
    conn.setInstanceFollowRedirects(false);
    conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    addCookies(conn);
    postData(conn, data);
    expectResponse(conn, 200, "Connection 2: ");
    getCookies(conn);
    String html = getFormValues(conn);
    conn.disconnect();

    /* this is really horrible */
    int start = html.indexOf("?ticket=");
    if (start == -1) {
        throw new IOException("Invalid login, unable to locate ticket");
    }
    start += "?ticket=".length();
    int end = html.indexOf("'", start);
    String ticket = html.substring(start, end);
    System.err.println("ticket: " + ticket);

    // connection 3...
    fv.clear();
    fv.put("ticket", ticket);

    conn = get("https://connect.garmin.com/post-auth/login", fv);
    conn.setInstanceFollowRedirects(false);
    addCookies(conn);
    for (int i = 0;; i++) {
        int code = conn.getResponseCode();
        System.err.println("attempt: " + i + " => code: " + code);
        getCookies(conn);
        if (code == 200)
            break;
        if (code != 302)
            break;
        List<String> fields = conn.getHeaderFields().get("location");
        conn.disconnect();
        conn = get(fields.get(0), null);
        conn.setInstanceFollowRedirects(false);
        addCookies(conn);
    }
    conn.disconnect();

    return Status.OK; // return checkLogin();
}

From source file:org.apache.jmeter.protocol.http.sampler.HTTPJavaImpl.java

/**
 * Extracts all the required headers for that particular URL request and
 * sets them in the <code>HttpURLConnection</code> passed in
 *
 * @param conn//from  ww w .  j  a  v a2  s .co  m
 *            <code>HttpUrlConnection</code> which represents the URL
 *            request
 * @param u
 *            <code>URL</code> of the URL request
 * @param headerManager
 *            the <code>HeaderManager</code> containing all the cookies
 *            for this <code>UrlConfig</code>
 * @param cacheManager the CacheManager (may be null)
 */
private void setConnectionHeaders(HttpURLConnection conn, URL u, HeaderManager headerManager,
        CacheManager cacheManager) {
    // Add all the headers from the HeaderManager
    if (headerManager != null) {
        CollectionProperty headers = headerManager.getHeaders();
        if (headers != null) {
            for (JMeterProperty jMeterProperty : headers) {
                Header header = (Header) jMeterProperty.getObjectValue();
                String n = header.getName();
                String v = header.getValue();
                conn.addRequestProperty(n, v);
            }
        }
    }
    if (cacheManager != null) {
        cacheManager.setHeaders(conn, u);
    }
}

From source file:fi.cosky.sdk.API.java

private <T extends BaseData> T sendRequestWithAddedHeaders(Verb verb, String url, Class<T> tClass,
        Object object, HashMap<String, String> headers) throws IOException {
    URL serverAddress;// w  ww . j a  v  a2s  . c  o  m
    HttpURLConnection connection;
    BufferedReader br;
    String result = "";
    try {
        serverAddress = new URL(url);
        connection = (HttpURLConnection) serverAddress.openConnection();
        connection.setInstanceFollowRedirects(false);
        boolean doOutput = doOutput(verb);
        connection.setDoOutput(doOutput);
        connection.setRequestMethod(method(verb));
        connection.setRequestProperty("Authorization", headers.get("authorization"));
        connection.addRequestProperty("Accept", "application/json");

        if (doOutput) {
            connection.addRequestProperty("Content-Length", "0");
            OutputStreamWriter os = new OutputStreamWriter(connection.getOutputStream());
            os.write("");
            os.flush();
            os.close();
        }
        connection.connect();

        if (connection.getResponseCode() == HttpURLConnection.HTTP_SEE_OTHER
                || connection.getResponseCode() == HttpURLConnection.HTTP_CREATED) {
            Link location = parseLocationLinkFromString(connection.getHeaderField("Location"));
            Link l = new Link("self", "/tokens", "GET", "", true);
            ArrayList<Link> links = new ArrayList<Link>();
            links.add(l);
            links.add(location);
            ResponseData data = new ResponseData();
            data.setLocation(location);
            data.setLinks(links);
            return (T) data;
        }

        if (connection.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
            System.out.println("Authentication expired: " + connection.getResponseMessage());
            if (retry && this.tokenData != null) {
                retry = false;
                this.tokenData = null;
                if (authenticate()) {
                    System.out.println(
                            "Reauthentication success, will continue with " + verb + " request on " + url);
                    return sendRequestWithAddedHeaders(verb, url, tClass, object, headers);
                }
            } else
                throw new IOException(
                        "Tried to reauthenticate but failed, please check the credentials and status of NFleet-API");
        }

        if (connection.getResponseCode() >= HttpURLConnection.HTTP_BAD_REQUEST
                && connection.getResponseCode() < HttpURLConnection.HTTP_INTERNAL_ERROR) {
            System.out.println("ErrorCode: " + connection.getResponseCode() + " "
                    + connection.getResponseMessage() + " " + url + ", verb: " + verb);

            String errorString = readErrorStreamAndCloseConnection(connection);
            throw (NFleetRequestException) gson.fromJson(errorString, NFleetRequestException.class);
        } else if (connection.getResponseCode() >= HttpURLConnection.HTTP_INTERNAL_ERROR) {
            if (retry) {
                System.out.println("Server responded with internal server error, trying again in "
                        + RETRY_WAIT_TIME + " msec.");
                try {
                    retry = false;
                    Thread.sleep(RETRY_WAIT_TIME);
                    return sendRequestWithAddedHeaders(verb, url, tClass, object, headers);
                } catch (InterruptedException e) {

                }
            } else {
                System.out.println("Server responded with internal server error, please contact dev@nfleet.fi");
            }

            String errorString = readErrorStreamAndCloseConnection(connection);
            throw new IOException(errorString);
        }

        result = readDataFromConnection(connection);
    } catch (MalformedURLException e) {
        throw e;
    } catch (ProtocolException e) {
        throw e;
    } catch (UnsupportedEncodingException e) {
        throw e;
    } catch (IOException e) {
        throw e;
    }
    return (T) gson.fromJson(result, tClass);
}

From source file:org.apache.jmeter.protocol.http.sampler.HTTPJavaImplClassifier.java

/**
 * Extracts all the required headers for that particular URL request and
 * sets them in the <code>HttpURLConnection</code> passed in
 * /*from w  ww.jav  a2  s. c o  m*/
 * @param conn
 *            <code>HttpUrlConnection</code> which represents the URL
 *            request
 * @param u
 *            <code>URL</code> of the URL request
 * @param headerManager
 *            the <code>HeaderManager</code> containing all the cookies for
 *            this <code>UrlConfig</code>
 * @param cacheManager
 *            the CacheManager (may be null)
 */
private void setConnectionHeaders(HttpURLConnection conn, URL u, HeaderManager headerManager,
        CacheManager cacheManager) {
    // Add all the headers from the HeaderManager
    if (headerManager != null) {
        CollectionProperty headers = headerManager.getHeaders();
        if (headers != null) {
            PropertyIterator i = headers.iterator();
            while (i.hasNext()) {
                Header header = (Header) i.next().getObjectValue();
                String n = header.getName();
                String v = header.getValue();
                conn.addRequestProperty(n, v);
            }
        }
    }
    if (cacheManager != null) {
        cacheManager.setHeaders(conn, u);
    }
}