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:jp.go.nict.langrid.servicecontainer.executor.jsonrpc.DynamicJsonRpcServiceExecutor.java

@Override
public Object invoke(Object proxy, final Method method, final Object[] args) throws Throwable {
    Map<String, Object> mimeHeaders = new HashMap<String, Object>();
    final List<RpcHeader> rpcHeaders = new ArrayList<RpcHeader>();
    Pair<Endpoint, Long> r = preprocessJsonRpc(mimeHeaders, rpcHeaders);
    Endpoint ep = r.getFirst();//from   www .  j  a  v  a 2s.c  om
    long s = System.currentTimeMillis();
    HttpURLConnection con = null;
    JsonRpcResponse ret = null;
    RpcFault fault = null;
    try {
        con = (HttpURLConnection) ep.getAddress().toURL().openConnection();
        con.setUseCaches(false);
        con.setDoOutput(true);
        con.setConnectTimeout(3000);
        con.setReadTimeout(10000);
        con.setRequestProperty("Accept", "application/json-rpc");
        con.setRequestProperty("Content-type", "application/json-rpc");
        con.setRequestProperty(LangridConstants.HTTPHEADER_PROTOCOL, Protocols.JSON_RPC);
        String authUserName = ep.getUserName();
        String authPassword = ep.getPassword();
        if (authUserName != null && authUserName.length() > 0) {
            String header = authUserName + ":" + ((authPassword != null) ? authPassword : "");
            con.setRequestProperty("Authorization",
                    "Basic " + new String(Base64.encodeBase64(header.getBytes())));
        }
        for (Map.Entry<String, Object> entry : mimeHeaders.entrySet()) {
            con.addRequestProperty(entry.getKey(), entry.getValue().toString());
        }
        OutputStream os = con.getOutputStream();
        JSON.encode(JsonRpcUtil.createRequest(rpcHeaders, method, args), os);
        os.flush();
        InputStream is = null;
        try {
            is = con.getInputStream();
        } catch (IOException e) {
            is = con.getErrorStream();
        } finally {
            if (is != null) {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                is = new DuplicatingInputStream(is, baos);
                try {
                    ret = JSON.decode(is, JsonRpcResponse.class);
                } catch (JSONException e) {
                    fault = new RpcFault("Server.userException", e.toString(),
                            ExceptionUtil.getMessageWithStackTrace(e) + "\nsource: "
                                    + new String(baos.toByteArray(), "UTF-8"));
                }
            } else {
                throw new RuntimeException("failed to open response stream.");
            }
        }
        if (ret.getError() != null) {
            fault = ret.getError();
            throw RpcFaultUtil.rpcFaultToThrowable(ret.getError());
        }
        return converter.convert(ret.getResult(), method.getReturnType());
    } finally {
        long dt = System.currentTimeMillis() - s;
        List<RpcHeader> resHeaders = null;
        if (ret != null && ret.getHeaders() != null) {
            resHeaders = Arrays.asList(ret.getHeaders());
        }
        postprocessJsonRpc(r.getSecond(), dt, con, resHeaders, fault);
        if (con != null)
            con.disconnect();
    }
}

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

private Status connectNew() throws MalformedURLException, IOException, JSONException {
    Status s = Status.NEED_AUTH;//from   www  . j ava2s .c  o m
    s.authMethod = Synchronizer.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);
    SyncHelper.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);
    Log.e(getName(), "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();
        Log.e(getName(), "attempt: " + i + " => code: " + code);
        getCookies(conn);
        if (code == HttpStatus.SC_OK)
            break;
        if (code != HttpStatus.SC_MOVED_TEMPORARILY)
            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:com.elevenpaths.googleindexretriever.GoogleSearch.java

public String responseCaptcha(String responseCaptcha) {
    String url = "https://ipv4.google.com/sorry/CaptchaRedirect";
    String request = url + "?q=" + q + "&hl=es&continue=" + continueCaptcha + "&id=" + idCaptcha + "&captcha="
            + responseCaptcha + "&submit=Enviar";
    String newCookie = "";

    try {/* w ww  .j  a  va  2 s .  c  o  m*/
        URL obj = new URL(request);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        // optional default is GET
        con.setRequestMethod("GET");

        // add request header
        con.setRequestProperty("Host", "ipv4.google.com");
        con.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:48.0) Gecko/20100101 Firefox/48.0");
        con.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
        con.setRequestProperty("Accept-Language", "es-ES,es;q=0.8,en-US;q=0.5,en;q=0.3");
        con.setRequestProperty("Accept-Encoding", "gzip, deflate, br");
        con.setRequestProperty("Cookie", tokenCookie + "; path=/; domain=google.com");
        con.addRequestProperty("Connection", "keep-alive");
        con.setRequestProperty("Referer", referer);
        //con.connect();
        boolean redirect = false;
        con.setInstanceFollowRedirects(false);
        int status = con.getResponseCode();

        if (status != HttpURLConnection.HTTP_OK) {
            if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM
                    || status == HttpURLConnection.HTTP_SEE_OTHER)
                redirect = true;
        }

        if (redirect) {

            // get redirect url from "location" header field
            String newUrl = con.getHeaderField("Location");

            // open the new connnection again
            con = (HttpURLConnection) new URL(newUrl).openConnection();
            con.setRequestProperty("User-Agent",
                    "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:48.0) Gecko/20100101 Firefox/48.0");
            con.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
            con.setRequestProperty("Referer", referer);
            con.setRequestProperty("Accept-Encoding", "gzip, deflate");
            con.setRequestProperty("Cookie", tokenCookie);
            con.addRequestProperty("Connection", "keep-alive");

            // Find the cookie
            String nextURL = URLDecoder.decode(newUrl, "UTF-8");
            String[] k = nextURL.split("&");
            for (String a : k) {
                if (a.startsWith("google_abuse=")) {
                    String temp = a.replace("google_abuse=", "");
                    String[] c = temp.split(";");
                    for (String j : c) {
                        if (j.startsWith("GOOGLE_ABUSE_EXEMPTION")) {
                            newCookie = j;
                        }
                    }

                }
            }
        }

        con.connect();

        if (con.getResponseCode() == 200) {
            newCookie = tokenCookie;
        }
    } catch (IOException e) {
        e.printStackTrace();

    }

    return newCookie;

}

From source file:it.infn.ct.pidAdmin_portlet.java

void deletePID(ActionRequest request) {

    _log.warn("STARTING DELETE REQUEST");

    String pidName = (String) request.getParameter("delete");

    try {//from  ww w .  j a  va  2s  .c  om
        String userpass = user + ":" + password;
        String encoded = new sun.misc.BASE64Encoder().encode(userpass.getBytes());

        URL url = new URL(uri + pidName);

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestProperty("Authorization", "Basic " + encoded);
        connection.addRequestProperty("Accept", "application/json");
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        connection.setRequestMethod("DELETE");

        OutputStream out = connection.getOutputStream();
        System.out.println("ERROR: " + connection.getResponseCode());
        System.out.println("URL: " + url.toString());

        out.close();
        System.out.println("DELETION REQUEST FINISHED");

        // Check here that you succeeded!
    } catch (Exception e) {
        System.out.println("HA cascado borrando un PID");
        e.printStackTrace();
    }

}

From source file:it.infn.ct.pidAdmin_portlet.java

void createPID(ActionRequest request) {
    _log.warn("STARTING CREATION REQUEST");

    String portlet = (String) request.getParameter("portlet");
    String inputPIDURL = (String) request.getParameter("inputPIDURL");
    String pidName = (String) request.getParameter("pidName");
    String infoToJSon = "[{\"type\":\"URL\",\"parsed_data\":\"" + inputPIDURL + "\"}]";

    try {//from  w ww  .  j  av a  2s .  co  m
        String userpass = user + ":" + password;
        String encoded = new sun.misc.BASE64Encoder().encode(userpass.getBytes());

        URL url = new URL(uri + portlet + "." + pidName);

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestProperty("Authorization", "Basic " + encoded);
        connection.addRequestProperty("Accept", "application/json");
        connection.addRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        connection.setRequestMethod("PUT");

        OutputStream out = connection.getOutputStream();
        out.write(infoToJSon.getBytes("UTF-8"));
        System.out.println("ERROR: " + connection.getResponseCode());

        out.close();
        System.out.println("CREATION REQUEST FINISHED");

        // Check here that you succeeded!
    } catch (Exception e) {
        System.out.println("HA cascado escribiendo un PID");
        e.printStackTrace();
    }

}

From source file:com.polyvi.xface.extension.filetransfer.XFileTransferExt.java

/**
 * ?/*ww w .  j a  v  a  2 s .c  o  m*/
 * @param headers       ?
 * @param conn          Http
 */
private void handleRequestHeader(JSONObject headers, HttpURLConnection conn) {
    if (headers != null) {
        try {
            for (Iterator iter = headers.keys(); iter.hasNext();) {
                String headerKey = iter.next().toString();
                JSONArray headerValues = headers.optJSONArray(headerKey);
                if (headerValues == null) {
                    headerValues = new JSONArray();
                    headerValues.put(headers.getString(headerKey));
                }
                conn.setRequestProperty(headerKey, headerValues.getString(0));
                for (int index = 1; index < headerValues.length(); ++index) {
                    conn.addRequestProperty(headerKey, headerValues.getString(index));
                }
            }
        } catch (JSONException e1) {
            XLog.d(CLASS_NAME, "No headers to be manipulated!");
        }
    }
}

From source file:org.openecomp.sdnc.uebclient.SdncUebCallback.java

private HttpURLConnection getRestXmlConnection(String urlString, String method) throws IOException {
    URL sdncUrl = new URL(urlString);
    Authenticator.setDefault(new SdncAuthenticator(config.getSdncUser(), config.getSdncPasswd()));

    HttpURLConnection conn = (HttpURLConnection) sdncUrl.openConnection();

    String authStr = config.getSdncUser() + ":" + config.getSdncPasswd();
    String encodedAuthStr = new String(Base64.encodeBase64(authStr.getBytes()));

    conn.addRequestProperty("Authentication", "Basic " + encodedAuthStr);

    conn.setRequestMethod(method);/*from   w w  w. j  av  a2 s. c  o  m*/
    conn.setRequestProperty("Content-Type", "application/xml");
    conn.setRequestProperty("Accept", "application/xml");

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

    return (conn);

}

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

private <T> void addMimeTypeAcceptToRequest(Object object, Class<T> tClass, HttpURLConnection connection) {
    Field f = null;//from  w w  w  . jav a  2 s  .c o  m
    StringTokenizer st = null;
    StringBuilder sb = null;
    Field[] fields = null;
    try {
        fields = object != null ? fields = object.getClass().getDeclaredFields() : tClass.getDeclaredFields();

        for (Field field : fields) {
            if (field.getName().equals("MimeType"))
                f = field;
        }
        if (f == null) {
            connection.setRequestProperty("Accept", "application/json");
            return;
        }

        String type = null;

        f.setAccessible(true);
        type = f.get(tClass).toString();

        if (type != null) {
            connection.addRequestProperty("Accept", helper.getSupportedType(type));
        }
    } catch (Exception e) {

    }
}

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

private <T> void addMimeTypeContentTypeToRequest(Object object, Class<T> tClass, HttpURLConnection connection) {
    Field f = null;/*  w  w  w  . j a  va 2  s . com*/
    StringTokenizer st = null;
    StringBuilder sb = null;
    Field[] fields = null;
    try {
        fields = object != null ? fields = object.getClass().getDeclaredFields() : tClass.getDeclaredFields();

        for (Field field : fields) {
            if (field.getName().equals("MimeType"))
                f = field;
        }

        if (f == null) {
            connection.setRequestProperty("Content-Type", "application/json");
            return;
        }

        String type = null;

        f.setAccessible(true);
        type = f.get(object).toString();

        if (type != null) {
            connection.addRequestProperty("Content-Type", helper.getSupportedType(type));
        }
    } catch (Exception e) {

    }
}