Example usage for java.net HttpURLConnection setDoOutput

List of usage examples for java.net HttpURLConnection setDoOutput

Introduction

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

Prototype

public void setDoOutput(boolean dooutput) 

Source Link

Document

Sets the value of the doOutput field for this URLConnection to the specified value.

Usage

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

public AccessToken refreshAccessToken(String authorityServerUri, String clientId, String clientSecret,
        String refreshToken, String scope) throws IOException, OAuthException {
    String content = "grant_type=refresh_token&refresh_token=" + URLEncoder.encode(refreshToken, "utf-8");
    if (scope != null && !scope.trim().isEmpty())
        content += "&scope=" + URLEncoder.encode(scope, "utf-8");
    String type = "application/x-www-form-urlencoded";
    URL u = new URL(authorityServerUri);
    HttpURLConnection conn = (HttpURLConnection) u.openConnection();
    conn.setDoOutput(true);
    String basicAuthentication = Base64.encodeBase64String((clientId + ":" + clientSecret).getBytes());
    conn.setRequestProperty("Authorization", "Basic " + basicAuthentication);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", type);
    conn.setRequestProperty("Content-Length", String.valueOf(content.length()));
    try (OutputStream os = conn.getOutputStream()) {
        os.write(content.getBytes());//  w  w w . j  a  va  2  s  .c  o  m
    }
    try (InputStream is = conn.getInputStream(); InputStreamReader reader = new InputStreamReader(is)) {
        AccessTokenResponse token = Serializer.fromJson(reader, AccessTokenResponse.class);
        if (token.error != null) {
            throw new OAuthException(token.error, token.errorDescription, token.errorUri);
        }
        return token;
    }
}

From source file:org.openmeetings.app.rss.LoadAtomRssFeed.java

public LinkedHashMap<String, LinkedHashMap<String, LinkedHashMap<String, Object>>> parseRssFeed(
        String urlEndPoint) {/* w w w.  j  a va 2 s  .c o  m*/
    try {
        LinkedHashMap<String, LinkedHashMap<String, LinkedHashMap<String, Object>>> lMap = new LinkedHashMap<String, LinkedHashMap<String, LinkedHashMap<String, Object>>>();

        URL url = new URL(urlEndPoint);

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

        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestProperty("user-agent",
                "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322)");
        conn.setRequestProperty("Referer", "http://incubator.apache.org/openmeetings/");
        conn.connect();

        SAXReader reader = new SAXReader();
        Document document = reader.read(conn.getInputStream());

        Element root = document.getRootElement();
        int l = 0;

        for (@SuppressWarnings("unchecked")
        Iterator<Element> i = root.elementIterator(); i.hasNext();) {
            Element item = i.next();
            LinkedHashMap<String, LinkedHashMap<String, Object>> items = new LinkedHashMap<String, LinkedHashMap<String, Object>>();
            boolean isSubElement = false;

            for (@SuppressWarnings("unchecked")
            Iterator<Element> it2 = item.elementIterator(); it2.hasNext();) {
                Element subItem = it2.next();

                LinkedHashMap<String, Object> itemObj = new LinkedHashMap<String, Object>();

                itemObj.put("name", subItem.getName());
                itemObj.put("text", subItem.getText());

                LinkedHashMap<String, String> attributes = new LinkedHashMap<String, String>();

                for (@SuppressWarnings("unchecked")
                Iterator<Attribute> attr = subItem.attributeIterator(); attr.hasNext();) {
                    Attribute at = attr.next();
                    attributes.put(at.getName(), at.getText());
                }
                itemObj.put("attributes", attributes);

                // log.error(subItem.getName()+ ": " +subItem.getText());
                items.put(subItem.getName(), itemObj);
                isSubElement = true;
            }

            if (isSubElement) {
                l++;
                lMap.put("item" + l, items);
            }

        }

        return lMap;

    } catch (Exception err) {
        log.error("[parseRssFeed]", err);
    }
    return null;

}

From source file:net.bashtech.geobot.BotManager.java

public static String putRemoteData(String urlString, String postData) throws IOException {

    URL url;//from w w w.j  av a 2  s.  co  m
    HttpURLConnection conn;

    try {
        url = new URL(urlString);

        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("PUT");

        conn.setFixedLengthStreamingMode(postData.getBytes().length);
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("Accept", "application/vnd.twitchtv.v2+json");
        conn.setRequestProperty("Authorization", "OAuth " + BotManager.getInstance().krakenOAuthToken);
        conn.setRequestProperty("Client-ID", BotManager.getInstance().krakenClientID);
        // conn.setConnectTimeout(5 * 1000);
        // conn.setReadTimeout(5 * 1000);

        PrintWriter out = new PrintWriter(conn.getOutputStream());
        out.print(postData);
        out.close();

        String response = "";

        Scanner inStream = new Scanner(conn.getInputStream());

        while (inStream.hasNextLine())
            response += (inStream.nextLine());

        return response;

    } catch (MalformedURLException ex) {
        ex.printStackTrace();
    }

    return "";
}

From source file:org.compose.mobilesdk.android.ServerRequestTask.java

public String doPUTRequest(URL requestUrl) {
    String responseString = null;

    try {//www. j a v a 2 s .  c  om
        HttpURLConnection httpCon = (HttpURLConnection) requestUrl.openConnection();
        httpCon.setDoOutput(true);
        httpCon.setDoInput(true);
        httpCon.setRequestMethod("PUT");
        httpCon.setRequestProperty("Content-Type", "application/json");
        httpCon.setRequestProperty("Authorization", header_parameters);
        httpCon.setRequestProperty("User-Agent", "Mozilla/5.0 ( compatible ) ");
        httpCon.setRequestProperty("Accept", "*/*");

        OutputStreamWriter out = new OutputStreamWriter(httpCon.getOutputStream());
        out.write("" + this.message);
        out.close();

        if (DEBUG) {
            BufferedReader in = null;
            if (httpCon.getErrorStream() != null)
                in = new BufferedReader(new InputStreamReader(httpCon.getErrorStream()));
            else
                in = new BufferedReader(new InputStreamReader(httpCon.getInputStream()));
            String inputLine;

            while ((inputLine = in.readLine()) != null) {

                Log.i(DEBUG_INFO, inputLine);
            }
            in.close();

        }

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

    return responseString;
}

From source file:com.cd.reddit.http.RedditRequestor.java

public RedditRequestResponse executePost(RedditRequestInput input) throws RedditException {
    HttpURLConnection connection = getConnection(input);

    connection.setDoOutput(true);

    try {/*  ww  w  .  j  a v a 2  s. com*/
        connection.setRequestMethod("POST");
    } catch (ProtocolException e) {
        throw new RedditException(e);
    }

    OutputStream outputStream = null;

    try {
        outputStream = connection.getOutputStream();
        IOUtils.write(generateUrlEncodedForm(input.getFormParams()), outputStream, "UTF-8");
    } catch (IOException e) {
        throw new RedditException(e);
    } finally {
        IOUtils.closeQuietly(outputStream);
    }

    return readResponse(connection, input);
}

From source file:net.peterkuterna.appengine.apps.devoxxsched.util.Md5Calculator.java

private byte[] getResponse(final String requestUri) {
    try {/*  w  w w . j  a  va  2  s .co  m*/
        URL url = new URL(requestUri);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestProperty("User-agent", "Devoxx Schedule AppEngine Backend");
        connection.setDoOutput(true);
        connection.setRequestMethod("GET");
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(120 * 1000);
        connection.setRequestProperty("Cache-Control", "no-cache,max-age=0");
        connection.setRequestProperty("Pragma", "no-cache");
        InputStream response = connection.getInputStream();
        log.info("response = " + connection.getResponseCode());
        if (connection.getResponseCode() == 200) {
            return IOUtils.toByteArray(response);
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:corner.payment.services.impl.processor.AlipayProcessor.java

@Override
public boolean verifyNotify(String notifyId) {
    if (notifyId == null) {
        throw new IllegalArgumentException("The notifyId is null");
    }/*  w w w  . ja va  2 s  .  co  m*/
    String alipayNotifyURL = String.format("%s?partner=%s&notify_id=%s", QUERY_URL, partner, notifyId);
    java.io.Closeable input = null;
    try {
        URL url = new URL(alipayNotifyURL);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setDoOutput(false);
        urlConnection.setConnectTimeout(30 * 1000);
        urlConnection.setReadTimeout(30 * 1000);
        BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
        input = in;
        String inputLine = in.readLine().toString();
        urlConnection.disconnect();
        if ("true".equalsIgnoreCase(inputLine)) {
            return true;
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (input != null) {
            try {
                input.close();
            } catch (IOException e) {
            }
        }
    }
    return false;
}

From source file:net.bashtech.geobot.BotManager.java

public static String postRemoteDataTwitch(String urlString, String postData, int krakenVersion) {
    URL url;/*from  w  ww . j  av  a 2s.c o  m*/
    HttpURLConnection conn;

    try {
        url = new URL(urlString);

        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");

        conn.setFixedLengthStreamingMode(postData.getBytes().length);
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Accept", "application/vnd.twitchtv.v" + krakenVersion + "+json");
        conn.setRequestProperty("Authorization", "OAuth " + BotManager.getInstance().krakenOAuthToken);
        conn.setRequestProperty("Client-ID", BotManager.getInstance().krakenClientID);
        // conn.setConnectTimeout(5 * 1000);
        // conn.setReadTimeout(5 * 1000);

        PrintWriter out = new PrintWriter(conn.getOutputStream());
        out.print(postData);
        out.close();

        String response = "";

        Scanner inStream = new Scanner(conn.getInputStream());

        while (inStream.hasNextLine())
            response += (inStream.nextLine());

        inStream.close();
        return response;

    } catch (MalformedURLException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    }

    return "";
}

From source file:fr.mixit.android.utils.NetworkUtils.java

@TargetApi(Build.VERSION_CODES.GINGERBREAD)
static ResponseHttp getInputStreamFromHttpUrlConnection(String url, boolean isPost, String args) {
    final ResponseHttp myResponse = new ResponseHttp();

    HttpURLConnection urlConnection = null;

    if (cookieManager == null) {
        cookieManager = new CookieManager();
        CookieHandler.setDefault(cookieManager);
    }/*from ww  w.j a v  a2 s  .co  m*/

    try {
        String urlWithParams = url;
        if (!isPost && args != null) {
            urlWithParams = getGetURL(url, args);
        }
        final URL urlObject = new URL(urlWithParams);
        urlConnection = (HttpURLConnection) urlObject.openConnection();
        urlConnection.setConnectTimeout(CONNECTION_TIMEOUT);
        urlConnection.setReadTimeout(SOCKET_TIMEOUT);

        // if (cookieSession != null) {
        // cookieManager.getCookieStore().removeAll();
        // cookieManager.getCookieStore().addCookie(cookieSession);
        // }

        if (isPost) {
            urlConnection.setDoOutput(true);
        }

        // urlConnection.connect();
        if (isPost && args != null) {
            final byte[] params = args.getBytes(HTTP.UTF_8);
            urlConnection.setFixedLengthStreamingMode(params.length);// or urlConnection.setChunkedStreamingMode(0);

            final OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
            out.write(params);
        }
        myResponse.status = urlConnection.getResponseCode();
        if (DEBUG_MODE) {
            Log.d(TAG, "Status code : " + myResponse.status);
        }
        myResponse.jsonText = getJson(urlConnection.getInputStream());
    } catch (final MalformedURLException e) {
        if (DEBUG_MODE) {
            Log.e(TAG, "The URL is malformatted", e);
        }
    } catch (final IllegalAccessError e) {
        if (DEBUG_MODE) {
            Log.e(TAG, "setDoOutput after openning a connection or already done");
        }
    } catch (final UnsupportedEncodingException e) {
        if (DEBUG_MODE) {
            Log.e(TAG, "UTF8 unsupported for args", e);
        }
    } catch (final IllegalStateException e) {
        if (DEBUG_MODE) {
            Log.e(TAG, "I/O Error", e);
        }
    } catch (final IllegalArgumentException e) {
        if (DEBUG_MODE) {
            Log.e(TAG, "I/O Error", e);
        }
    } catch (final IOException e) {
        if (DEBUG_MODE) {
            Log.e(TAG, "I/O Error", e);
        }
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
    return myResponse;
}

From source file:de.rallye.test.GroupsTest.java

@Test
public void testLogin() throws IOException {

    Authenticator.setDefault(new Authenticator() {
        @Override//from  w w w .j  av a  2  s.  c  o  m
        protected PasswordAuthentication getPasswordAuthentication() {
            String realm = getRequestingPrompt();
            assertEquals("Should be right Realm", "RallyeNewUser", realm);
            return new PasswordAuthentication(String.valueOf(1), "test".toCharArray());
        }
    });
    URL url = new URL("http://127.0.0.1:10111/groups/1");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("PUT");

    conn.setDoOutput(true);
    conn.addRequestProperty("Content-Type", "application/json");
    //      conn.setFixedLengthStreamingMode(post.length);
    conn.getOutputStream().write(MockDataAdapter.validLogin.getBytes());

    int code = conn.getResponseCode();

    Authenticator.setDefault(null);

    try {
        assertEquals("Code should be 200", 200, code);
    } catch (AssertionError e) {
        System.err.println("This is the content:");
        List<String> contents = IOUtils.readLines((InputStream) conn.getContent());
        for (String line : contents)
            System.err.println(line);
        throw e;
    }

}