Example usage for java.net URLConnection setRequestProperty

List of usage examples for java.net URLConnection setRequestProperty

Introduction

In this page you can find the example usage for java.net URLConnection setRequestProperty.

Prototype

public void setRequestProperty(String key, String value) 

Source Link

Document

Sets the general request property.

Usage

From source file:edu.caltech.ipac.firefly.server.query.IpacTablePartProcessor.java

public void downloadFile(URL url, File outFile) throws IOException, EndUserException {
    URLConnection conn = null;
    try {/*from   w  w w.  ja va2s .  co  m*/
        Map<String, String> cookies = isSecurityAware() ? ServerContext.getRequestOwner().getIdentityCookies()
                : null;
        conn = URLDownload.makeConnection(url, cookies);
        conn.setRequestProperty("Accept", "*/*");
        URLDownload.getDataToFile(conn, outFile);

    } catch (MalformedURLException e) {
        LOGGER.error(e, "Bad URL");
        throw makeException(e, "WISE Query Failed - bad url.");

    } catch (FailedRequestException e) {
        LOGGER.error(e, e.toString());
        if (conn != null && conn instanceof HttpURLConnection) {
            HttpURLConnection httpConn = (HttpURLConnection) conn;
            int respCode = httpConn.getResponseCode();
            String desc = respCode == 200 ? e.getMessage() : HttpStatus.getStatusText(respCode);
            throw new EndUserException("Search Failed: " + desc, e.getDetailMessage(), e);
        } else {
            throw makeException(e, "Query Failed - network error.");
        }
    } catch (IOException e) {
        if (conn != null && conn instanceof HttpURLConnection) {
            HttpURLConnection httpConn = (HttpURLConnection) conn;
            int respCode = httpConn.getResponseCode();
            String desc = respCode == 200 ? e.getMessage() : HttpStatus.getStatusText(respCode);
            throw new EndUserException("Search Failed: " + desc, e.getMessage(), e);
        } else {
            throw makeException(e, "Query Failed - network error.");
        }
    }
}

From source file:ca.inverse.sogo.security.SOGoOfficer.java

/**
 * /*from  www  . j  a v a  2s  .c o  m*/
 * @param host
 * @param username
 * @param credentials
 * @return
 */
private boolean checkSOGoCredentials(String host, String username, String credentials, SOGoUser user) {
    try {
        URLConnection conn;
        URL url;
        // host has the following format:  sogo.acme.com
        // We have to rebuild the URL using: http://sogo.acme.com/SOGo/dav/<username>/freebusy.ifb
        //url = new URL("http://" + host + ":8999/SOGo/dav/" + username + "/freebusy.ifb");          
        url = new URL("http", host, Integer.parseInt(_port), "/SOGo/dav/" + username + "/freebusy.ifb");
        conn = url.openConnection();
        conn.setRequestProperty("Authorization", "Basic " + credentials);
        conn.getInputStream();

        //ClassLoader savedClassLoader = Thread.currentThread().getContextClassLoader();
        //Thread.currentThread().setContextClassLoader( this.getClass().getClassLoader() );
        //Class.forName("org.apache.xerces.parsers.XML11Configuration");
        //System.setProperty("javax.xml.parsers.DocumentBuilderFactory", "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");

        //          PropFindMethod pf;
        //            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        //            DocumentBuilder builder = factory.newDocumentBuilder();
        //
        //            String s = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
        //                                "<D:propfind xmlns:D=\"DAV:\">" +
        //                                  "<D:prop>" +
        //                                    "<D:owner/>" +
        //                                  "</D:prop>" +
        //                                "</D:propfind>";
        //
        //            ByteArrayInputStream stream;
        //            stream = new ByteArrayInputStream(s.getBytes());
        //            Document doc = builder.parse(stream);
        //
        //            pf = new PropFindMethod("http://" + host + "/SOGo/dav/" + username + "/freebusy.ifb", DavConstants.PROPFIND_BY_PROPERTY, DavConstants.DEPTH_1);
        //            pf.setRequestBody(doc);
        //
        //            HttpClient client = new HttpClient();
        //            HostConfiguration hc = new HostConfiguration();
        //            hc.setHost(host, 80);
        //
        //            client.getParams().setAuthenticationPreemptive(true);
        //            Credentials defaultcreds = new UsernamePasswordCredentials(username, password);
        //            client.getState().setCredentials(new AuthScope(host, 80, AuthScope.ANY_REALM), defaultcreds);
        //            client.executeMethod(hc, pf);
        //           
        //            Document d = pf.getResponseBodyAsDocument();
        //
        //            Node n = (Node)d.getFirstChild().getFirstChild();
        //
        //            NodeList l;
        //            l = ((Element)n).getElementsByTagName("D:owner");
        //            l = ((Element)l.item(0)).getElementsByTagName("D:href");
        //            s =  DomUtil.getText((Element)l.item(0));
        //
        //            int a;
        //
        //            a = s.lastIndexOf('/', s.length()-2);
        //            s =  s.substring(a+1);
        //            if (s.endsWith("/")) s = s.substring(0, s.length()-1);
        //            System.out.println("userid = " + s);

        user.setUserID(username);

        //Thread.currentThread().setContextClassLoader( savedClassLoader );

        return true;
    } catch (Exception e) {
        _log.log(Level.WARNING, "Unable to check SOGo credentials. Invalid host, username or password.", e);
        _log.info("The host that was used is: " + host);
        _log.info("The username that was used is: " + username);
        //_log.info("The password that was used is: " + password);
    }

    return false;
}

From source file:test.security.ClassSecurityTest.java

/**
 * Uses Get XML query API, which takes a Detached  
 * Criteria object parameter./*from   w  w w  .j ava 2  s.  co m*/
 * Verifies that the results are returned 
 * Verifies size of the result set
 * Verifies that none of the attributes are null 
 * since user1 has access to all target class attributes
 * 
 * @throws Exception
 */
public void testBasicAuthenticationGetXML() throws Exception {
    if (enableCaGridLoginModule) {
        return;
    }
    Class bankKlass = Bank.class;

    try {
        String searchUrl = getServerURL() + "/GetXML?query=" + bankKlass.getName() + "&" + bankKlass.getName();
        URL url = new URL(searchUrl);
        URLConnection conn = url.openConnection();

        //String base64 = "/O=caBIG/OU=caGrid/OU=Training/OU=Dorian/CN=SDKUser1" + ":" + "Psat123!@#";
        String base64 = "SDKUser1" + ":" + "Psat123!@#";
        conn.setRequestProperty("Authorization", "Basic " + new String(Base64.encodeBase64(base64.getBytes())));

        File myFile = new File(bankKlass.getName() + "_test-getxml.xml");
        FileWriter myWriter = new FileWriter(myFile);
        DataInputStream dis = new DataInputStream(conn.getInputStream());

        String s, buffer = null;
        while ((s = dis.readLine()) != null) {
            myWriter.write(s);
            buffer = buffer + s;
        }

        myWriter.close();

        assertTrue(buffer.indexOf("<recordCounter>4</recordCounter>") > 0);

        for (int i = 1; i <= 4; i++) {
            assertTrue(buffer.indexOf(
                    "name=\"gov.nih.nci.cacoresdk.domain.inheritance.childwithassociation.Bank\" recordNumber=\""
                            + i + "\"") > 0);
            assertTrue(buffer.indexOf("<field name=\"id\">" + i + "</field>") > 0);
            if (enableAttributeLevelSecurity) {
                //assertTrue(buffer.indexOf("<field name=\"name\">-</field>") > 0);
                assertTrue(buffer.indexOf("<field name=\"name\">Bank" + i + "</field>") > 0);
            } else {
                assertTrue(buffer.indexOf("<field name=\"name\">Bank" + i + "</field>") > 0);
            }

        }
        myFile.delete();
    } catch (Exception e) {
        fail("Exception caught: " + e.getMessage());
    }
}

From source file:info.magnolia.cms.exchange.simple.SimpleSyndicator.java

/**
 * add request headers needed for this activation
 *
 * @param connection//w w  w .jav  a  2  s  . co  m
 * @param activationContent
 */
protected void addActivationHeaders(URLConnection connection, ActivationContent activationContent) {
    Iterator headerKeys = activationContent.getProperties().keySet().iterator();
    while (headerKeys.hasNext()) {
        String key = (String) headerKeys.next();
        String value = activationContent.getproperty(key);
        connection.setRequestProperty(key, value);
    }
}

From source file:adams.flow.transformer.DownloadContent.java

/**
 * Executes the flow item.//  ww w .j a v a2s  .co m
 *
 * @return      null if everything is fine, otherwise error message
 */
@Override
@MixedCopyright(author = "http://stackoverflow.com/users/2920131/lboix", license = License.CC_BY_SA_3, url = "http://stackoverflow.com/a/13122190", note = "handling basic authentication")
protected String doExecute() {
    String result;
    URL url;
    BufferedInputStream input;
    byte[] buffer;
    byte[] bufferSmall;
    int len;
    StringBuilder content;
    URLConnection conn;
    String basicAuth;

    input = null;
    content = new StringBuilder();
    try {
        if (m_InputToken.getPayload() instanceof String)
            url = new URL((String) m_InputToken.getPayload());
        else if (m_InputToken.getPayload() instanceof BaseURL)
            url = ((BaseURL) m_InputToken.getPayload()).urlValue();
        else
            url = (URL) m_InputToken.getPayload();

        conn = url.openConnection();
        if (url.getUserInfo() != null) {
            basicAuth = "Basic " + new String(new Base64().encode(url.getUserInfo().getBytes()));
            conn.setRequestProperty("Authorization", basicAuth);
        }
        input = new BufferedInputStream(conn.getInputStream());
        buffer = new byte[m_BufferSize];
        while ((len = input.read(buffer)) > 0) {
            if (len < m_BufferSize) {
                bufferSmall = new byte[len];
                System.arraycopy(buffer, 0, bufferSmall, 0, len);
                content.append(new String(bufferSmall));
            } else {
                content.append(new String(buffer));
            }
        }

        m_OutputToken = new Token(content.toString());
        content = null;
        result = null;
    } catch (Exception e) {
        result = handleException("Problem downloading '" + m_InputToken.getPayload() + "': ", e);
    } finally {
        try {
            if (input != null)
                input.close();
        } catch (Exception e) {
            // ignored
        }
    }

    return result;
}

From source file:com.android.sdklib.repository.legacy.remote.internal.DownloadCache.java

/**
 * Calls {@link HttpConfigurable#openHttpConnection(String)}
 * to actually perform a download.// w  w w.  j  av  a 2 s. c o m
 * <p>
 * Isolated so that it can be overridden by unit tests.
 */
@VisibleForTesting(visibility = Visibility.PRIVATE)
@NonNull
protected Pair<InputStream, URLConnection> openUrl(@NonNull String url, boolean needsMarkResetSupport,
        @NonNull ITaskMonitor monitor, @Nullable Header[] headers) throws IOException {
    URLConnection connection = new URL(url).openConnection();
    if (headers != null) {
        for (Header header : headers) {
            connection.setRequestProperty(header.getName(), header.getValue());
        }
    }
    connection.connect();
    InputStream is = connection.getInputStream();
    if (needsMarkResetSupport) {
        is = ensureMarkReset(is);
    }

    return Pair.of(is, connection);
}

From source file:com.krawler.spring.mailIntegration.mailIntegrationController.java

public JSONObject getRecentEmailDetails(HttpServletRequest request, String recid, String emailadd)
        throws ServiceException {
    JSONObject jobj = new JSONObject();
    try {//w  w  w . ja v  a2 s .com
        DateFormat userdft = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+00:00"));
        String dateFormatId = sessionHandlerImpl.getDateFormatID(request);
        String timeFormatId = sessionHandlerImpl.getUserTimeFormat(request);
        String timeZoneDiff = sessionHandlerImpl.getTimeZoneDifference(request);
        String userid = sessionHandlerImpl.getUserid(request);
        userdft = KwlCommonTablesDAOObj.getUserDateFormatter(dateFormatId, timeFormatId, timeZoneDiff);
        String url = StorageHandler.GetSOAPServerUrl();
        String res = "";
        String str = "";
        String pass = "";
        String currUser = sessionHandlerImplObj.getUserName(request) + "_";
        String jsonStr = profileHandlerDAOObj.getUser_hash(userid);
        //String emailadd = request.getParameter("email");
        JSONObject currUserAuthInfo = new JSONObject(jsonStr);
        if (currUserAuthInfo.has("userhash")) {
            currUser += currUserAuthInfo.getString("subdomain");
            pass = currUserAuthInfo.getString("userhash");
        }
        str = "username=" + currUser + "&user_hash=" + pass;
        str = str
                + "&action=EmailUIAjax&emailUIAction=rebuildShowAccount&krawler_body_only=true&module=Emails&to_pdf=true";

        URL u = new URL(url + "krawlermails.php");
        URLConnection uc = u.openConnection();
        uc.setDoOutput(true);
        uc.setUseCaches(false);
        uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        PrintWriter pw = new PrintWriter(uc.getOutputStream());
        pw.println(str);
        pw.close();
        BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
        String line = "";

        while ((line = in.readLine()) != null) {
            res += line;
        }
        in.close();
        boolean flag = true;
        try {
            JSONArray jarr = new JSONArray(res);
        } catch (JSONException ex) {
            flag = false;
        }
        if (flag) {
            String ieId = "";
            JSONArray jarr = new JSONArray(res);
            for (int cnt = 0; cnt < jarr.length(); cnt++) {
                JSONObject tempObj = jarr.getJSONObject(cnt);
                if (!StringUtil.isNullOrEmpty(tempObj.getString("value"))) {
                    ieId += tempObj.getString("value") + ",";
                }
            }

            if (ieId.length() > 0) {
                ieId = ieId.substring(0, ieId.length() - 1);
                str = "username=" + currUser + "&user_hash=" + pass;
                str = str + "&ieId=" + ieId + "&fromaddr=" + emailadd + "&mbox=INBOX";
                res = StringUtil.makeExternalRequest(url + "getSendersMails.php", str);
            } else {
                res = "{\"count\":0,\"data\":{}}";
            }

            JSONObject resJobj = new JSONObject();
            try {
                resJobj = new JSONObject(res);
            } catch (Exception ex) {
                resJobj = new JSONObject("{\"count\":0,\"data\":{}}");
            }
            JSONArray FinalArr = new JSONArray();
            if (resJobj.optInt("count", 0) > 0) {
                JSONArray jArr = resJobj.getJSONArray("data");
                for (int i = 0; i < jArr.length(); i++) {
                    JSONObject tmpobj = jArr.getJSONObject(i);
                    Date sendDateObj = sdf.parse(tmpobj.getString("senddate"));
                    String senddate = userdft.format(sendDateObj);
                    JSONObject obj = new JSONObject();
                    obj.put("docid", tmpobj.getString("imap_uid"));
                    obj.put("subject", tmpobj.getString("subject"));
                    obj.put("fromaddr", tmpobj.getString("fromaddr"));
                    obj.put("toaddr", tmpobj.getString("toaddr"));
                    obj.put("senddate", senddate);
                    obj.put("ie_id", tmpobj.getString("ie_id"));
                    obj.put("seen", tmpobj.getString("seen"));
                    //                    obj.put("time", AuthHandler.getUserDateFormatter(request, session).format(sdf.parse(tmpobj.getString("senddate"))));
                    obj.put("time", senddate);
                    obj.put("timeobj", sendDateObj);
                    obj.put("details", tmpobj.getString("subject"));
                    obj.put("folder", "Inbox");
                    obj.put("imgsrc", "../../images/inbox.png");
                    FinalArr.put(obj);
                }
            }

            // fetched Sent Items

            // get sent folder id
            //            String sentid = "";
            //            str = "username="+currUser+"&user_hash="+pass;
            //            str = str + "&action=EmailUIAjax&emailUIAction=refreshKrawlerFolders&krawler_body_only=true&module=Emails&to_pdf=true";
            //            res = StringUtil.makeExternalRequest(url+"getSendersMails.php",str);
            //            resJobj = new JSONObject(res);
            //            if(resJobj.has("children")) {
            //                JSONArray childArray = resJobj.getJSONArray("children");
            //                for(int cnt = 0; cnt< childArray.length(); cnt++) {
            //                    if(childArray.getJSONObject(cnt).getString("folder_type").equals("folder_type")) {
            //                        sentid = childArray.getJSONObject(cnt).getString("folder_type");
            //                    }
            //                }
            //            }
            //
            //            if(!StringUtil.isNullOrEmpty(sentid)) {
            //                str = "username="+currUser+"&user_hash="+pass;
            //                str = str + "&action=EmailUIAjax&emailUIAction=getMessageListKrawlerFoldersXML&module=Emails&to_pdf=true&start=0&limit=20&forceRefresh=false&mbox=Sent%20Emails&ieId="+sentid;
            //                res = StringUtil.makeExternalRequest(url+"krawlermails.php",str);
            //            }

            str = "userid=" + userid + "&username=" + currUser + "&user_hash=" + pass;
            str = str + "&fromaddr=" + emailadd + "&mbox=sent";
            res = StringUtil.makeExternalRequest(url + "getSendersMails.php", str);
            try {
                resJobj = new JSONObject(res);
            } catch (Exception ex) {
                resJobj = new JSONObject("{\"count\":0,\"data\":{}}");
            }
            if (resJobj.optInt("count", 0) > 0) {
                JSONArray jArr = resJobj.getJSONArray("data");
                for (int i = 0; i < jArr.length(); i++) {
                    JSONObject tmpobj = jArr.getJSONObject(i);
                    Date sendDateObj = sdf.parse(tmpobj.getString("date_sent"));
                    String senddate = userdft.format(sendDateObj);
                    JSONObject obj = new JSONObject();
                    obj.put("docid", tmpobj.getString("id"));
                    obj.put("subject", tmpobj.getString("name"));
                    obj.put("fromaddr", tmpobj.getString("from_addr"));
                    obj.put("toaddr", tmpobj.getString("to_addrs"));
                    obj.put("senddate", senddate);
                    //                    obj.put("ie_id", tmpobj.getString("ieId"));
                    obj.put("seen", tmpobj.getString("status").equals("unread") ? 0 : 1);
                    obj.put("time", senddate);
                    obj.put("details", tmpobj.getString("name"));
                    obj.put("timeobj", sendDateObj);
                    obj.put("folder", "Sent Item");
                    obj.put("imgsrc", "../../images/outbox.png");
                    FinalArr.put(obj);
                }
            }

            for (int i = 0; i < FinalArr.length(); i++) {
                for (int j = 0; j < FinalArr.length(); j++) {
                    if (((Date) (FinalArr.getJSONObject(i).get("timeobj")))
                            .after((Date) (FinalArr.getJSONObject(j).get("timeobj")))) {
                        JSONObject jobj1 = FinalArr.getJSONObject(i);
                        FinalArr.put(i, FinalArr.getJSONObject(j));
                        FinalArr.put(j, jobj1);
                    }
                }
            }
            jobj.put("emailList", FinalArr);
        } else {
            jobj.put("emailList", new JSONArray());
        }

    } catch (JSONException e) {
        throw ServiceException.FAILURE(e.getMessage(), e);
    } catch (SessionExpiredException e) {
        throw ServiceException.FAILURE(e.getMessage(), e);
    } catch (HibernateException e) {
        throw ServiceException.FAILURE(e.getMessage(), e);
    } catch (Exception e) {
        throw ServiceException.FAILURE(e.getMessage(), e);
    }
    return jobj;
}

From source file:bolts.WebViewAppLinkResolver.java

@Override
public Task<AppLink> getAppLinkFromUrlInBackground(final Uri url) {
    final Capture<String> content = new Capture<String>();
    final Capture<String> contentType = new Capture<String>();
    return Task.callInBackground(new Callable<Void>() {
        @Override//w  w  w.  java 2  s  .c  om
        public Void call() throws Exception {
            URL currentURL = new URL(url.toString());
            URLConnection connection = null;
            while (currentURL != null) {
                // Fetch the content at the given URL.
                connection = currentURL.openConnection();
                if (connection instanceof HttpURLConnection) {
                    // Unfortunately, this doesn't actually follow redirects if they go from http->https,
                    // so we have to do that manually.
                    ((HttpURLConnection) connection).setInstanceFollowRedirects(true);
                }
                connection.setRequestProperty(PREFER_HEADER, META_TAG_PREFIX);
                connection.connect();

                if (connection instanceof HttpURLConnection) {
                    HttpURLConnection httpConnection = (HttpURLConnection) connection;
                    if (httpConnection.getResponseCode() >= 300 && httpConnection.getResponseCode() < 400) {
                        currentURL = new URL(httpConnection.getHeaderField("Location"));
                        httpConnection.disconnect();
                    } else {
                        currentURL = null;
                    }
                } else {
                    currentURL = null;
                }
            }

            try {
                content.set(readFromConnection(connection));
                contentType.set(connection.getContentType());
            } finally {
                if (connection instanceof HttpURLConnection) {
                    ((HttpURLConnection) connection).disconnect();
                }
            }
            return null;
        }
    }).onSuccessTask(new Continuation<Void, Task<JSONArray>>() {
        @Override
        public Task<JSONArray> then(Task<Void> task) throws Exception {
            // Load the content in a WebView and use JavaScript to extract the meta tags.
            final TaskCompletionSource<JSONArray> tcs = new TaskCompletionSource<>();
            final WebView webView = new WebView(context);
            webView.getSettings().setJavaScriptEnabled(true);
            webView.setNetworkAvailable(false);
            webView.setWebViewClient(new WebViewClient() {
                private boolean loaded = false;

                private void runJavaScript(WebView view) {
                    if (!loaded) {
                        // After the first resource has been loaded (which will be the pre-populated data)
                        // run the JavaScript meta tag extraction script
                        loaded = true;
                        view.loadUrl(TAG_EXTRACTION_JAVASCRIPT);
                    }
                }

                @Override
                public void onPageFinished(WebView view, String url) {
                    super.onPageFinished(view, url);
                    runJavaScript(view);
                }

                @Override
                public void onLoadResource(WebView view, String url) {
                    super.onLoadResource(view, url);
                    runJavaScript(view);
                }
            });
            // Inject an object that will receive the JSON for the extracted JavaScript tags
            webView.addJavascriptInterface(new Object() {
                @JavascriptInterface
                public void setValue(String value) {
                    try {
                        tcs.trySetResult(new JSONArray(value));
                    } catch (JSONException e) {
                        tcs.trySetError(e);
                    }
                }
            }, "boltsWebViewAppLinkResolverResult");
            String inferredContentType = null;
            if (contentType.get() != null) {
                inferredContentType = contentType.get().split(";")[0];
            }
            webView.loadDataWithBaseURL(url.toString(), content.get(), inferredContentType, null, null);
            return tcs.getTask();
        }
    }, Task.UI_THREAD_EXECUTOR).onSuccess(new Continuation<JSONArray, AppLink>() {
        @Override
        public AppLink then(Task<JSONArray> task) throws Exception {
            Map<String, Object> alData = parseAlData(task.getResult());
            AppLink appLink = makeAppLinkFromAlData(alData, url);
            return appLink;
        }
    });
}

From source file:org.xbmc.jsonrpc.Connection.java

/**
 * Executes a query.// ww  w  .  jav a  2 s  . com
 * @param command    Name of the command to execute
 * @param parameters Parameters
 * @param manager    Reference back to business layer
 * @return Parsed JSON object, empty object on error.
 */
public JsonNode query(String command, JsonNode parameters, INotifiableManager manager) {
    URLConnection uc = null;
    try {
        final ObjectMapper mapper = Client.MAPPER;

        if (mUrlSuffix == null) {
            throw new NoSettingsException();
        }

        final URL url = new URL(mUrlSuffix + XBMC_JSONRPC_BOOTSTRAP);
        uc = url.openConnection();
        uc.setConnectTimeout(SOCKET_CONNECTION_TIMEOUT);
        uc.setReadTimeout(mSocketReadTimeout);
        if (authEncoded != null) {
            uc.setRequestProperty("Authorization", "Basic " + authEncoded);
        }
        uc.setRequestProperty("Content-Type", "application/json");
        uc.setDoOutput(true);

        final ObjectNode data = Client.obj().p("jsonrpc", "2.0").p("method", command).p("id", "1");
        if (parameters != null) {
            data.put("params", parameters);
        }

        final JsonFactory jsonFactory = new JsonFactory();
        final JsonGenerator jg = jsonFactory.createJsonGenerator(uc.getOutputStream(), JsonEncoding.UTF8);
        jg.setCodec(mapper);

        // POST data
        jg.writeTree(data);
        jg.flush();

        final JsonParser jp = jsonFactory.createJsonParser(uc.getInputStream());
        jp.setCodec(mapper);
        final JsonNode ret = jp.readValueAs(JsonNode.class);
        return ret;

    } catch (MalformedURLException e) {
        manager.onError(e);
    } catch (IOException e) {
        int responseCode = -1;
        try {
            responseCode = ((HttpURLConnection) uc).getResponseCode();
        } catch (IOException e1) {
        } // do nothing, getResponse code failed so treat as default i/o exception.
        if (uc != null && responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
            manager.onError(new HttpException(Integer.toString(HttpURLConnection.HTTP_UNAUTHORIZED)));
        } else {
            manager.onError(e);
        }
    } catch (NoSettingsException e) {
        manager.onError(e);
    }
    return new ObjectNode(null);
}