Example usage for java.net HttpURLConnection getOutputStream

List of usage examples for java.net HttpURLConnection getOutputStream

Introduction

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

Prototype

public OutputStream getOutputStream() throws IOException 

Source Link

Document

Returns an output stream that writes to this connection.

Usage

From source file:de.zib.scalaris.examples.wikipedia.plugin.fourcaast.FourCaastAccounting.java

protected void pushSdrToServer(final WikiPageBeanBase page) {
    if (!page.getServiceUser().isEmpty()) {
        final String sdr = createSdr(page);
        //            System.out.println("Sending sdr...\n" + sdr);
        try {/*  w  w w.  ja  v a 2s. c  o m*/
            HttpURLConnection urlConn = (HttpURLConnection) accountingServer.openConnection();
            urlConn.setDoOutput(true);
            urlConn.setRequestMethod("PUT");
            OutputStreamWriter out = new OutputStreamWriter(urlConn.getOutputStream());
            out.write(sdr);
            out.close();

            //read the result from the server (necessary for the request to be send!)
            BufferedReader in = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = in.readLine()) != null) {
                sb.append(line + '\n');
            }
            //                System.out.println(sb.toString());
            in.close();
        } catch (ProtocolException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

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

@Test
public void testLogin() throws IOException {

    Authenticator.setDefault(new Authenticator() {
        @Override//w ww.  j  a va  2 s .co  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;
    }

}

From source file:org.sample.nonblocking.TestClient.java

/**
 * Processes requests for both HTTP/* w w  w.j a  v  a2 s  . co m*/
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet TestClient</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Servlet TestClient at " + request.getContextPath() + "</h1>");

        String path = "http://" + request.getServerName() + ":" + request.getServerPort()
                + request.getContextPath() + "/ReadTestServlet";
        out.println("Invoking the endpoint: " + path + "<br>");
        out.flush();
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setChunkedStreamingMode(2);
        conn.setDoOutput(true);
        conn.connect();
        try (BufferedWriter output = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream()))) {
            out.println("Sending data ..." + "<br>");
            out.flush();
            output.write("Hello");
            output.flush();
            out.println("Sleeping ..." + "<br>");
            out.flush();
            Thread.sleep(5000);
            out.println("Sending more data ..." + "<br>");
            out.flush();
            output.write("World");
            output.flush();
            output.close();
        }
        out.println("<br><br>Check GlassFish server.log");
        out.println("</body>");
        out.println("</html>");
    } catch (InterruptedException | IOException ex) {
        Logger.getLogger(ReadTestServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.android.volley.toolbox.http.HurlStack.java

@SuppressWarnings("deprecation")
/* package */ static void setConnectionParametersForRequest(HttpURLConnection connection, Request<?> request)
        throws IOException, AuthFailureError {
    switch (request.getMethod()) {
    case Method.DEPRECATED_GET_OR_POST:
        // This is the deprecated way that needs to be handled for backwards compatibility.
        // If the request's post body is null, then the assumption is that the request is
        // GET.  Otherwise, it is assumed that the request is a POST.
        byte[] postBody = request.getBody();
        if (postBody != null) {
            // Prepare output. There is no need to set Content-Length explicitly,
            // since this is handled by HttpURLConnection using the size of the prepared
            // output stream.
            connection.setDoOutput(true);
            connection.setRequestMethod("POST");
            connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getBodyContentType());
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            out.write(postBody);//from   ww  w. j a  v  a2 s  . c o  m
            out.close();
        }
        break;
    case Method.GET:
        // Not necessary to set the request method because connection defaults to GET but
        // being explicit here.
        connection.setRequestMethod("GET");
        break;
    case Method.DELETE:
        connection.setRequestMethod("DELETE");
        break;
    case Method.POST:
        connection.setRequestMethod("POST");
        addBodyIfExists(connection, request);
        break;
    case Method.PUT:
        connection.setRequestMethod("PUT");
        addBodyIfExists(connection, request);
        break;
    case Method.HEAD:
        connection.setRequestMethod("HEAD");
        break;
    case Method.OPTIONS:
        connection.setRequestMethod("OPTIONS");
        break;
    case Method.TRACE:
        connection.setRequestMethod("TRACE");
        break;
    case Method.PATCH:
        //connection.setRequestMethod("PATCH");
        //If server doesnt support patch uncomment this
        connection.setRequestMethod("POST");
        connection.setRequestProperty("X-HTTP-Method-Override", "PATCH");
        addBodyIfExists(connection, request);
        break;
    default:
        throw new IllegalStateException("Unknown method type.");
    }
}

From source file:de.hybris.platform.marketplaceintegrationbackoffice.utils.MarketplaceintegrationbackofficeHttpUtilImpl.java

/**
 * Post data/*from   w  ww . java2  s . c o  m*/
 *
 * @param url
 * @param data
 * @return boolean
 * @throws IOException
 */
@Override
public boolean post(final String url, final String data) throws IOException {
    httpURL = new URL(url);
    final HttpURLConnection conn = (HttpURLConnection) httpURL.openConnection();
    conn.setDoOutput(true);
    initConnection(conn);
    OutputStreamWriter writer = null;
    OutputStream outStream = null;
    try {
        outStream = conn.getOutputStream();
        writer = new OutputStreamWriter(outStream, "UTF-8");
        writer.write(data);
        writer.flush();
    } finally {
        if (outStream != null) {
            try {
                outStream.close();
            } catch (final IOException ex) {
                LOG.error(ex.getMessage(), ex);
            }
        }
        if (writer != null) {
            try {
                writer.close();
            } catch (final IOException ex) {
                LOG.error(ex.getMessage(), ex);
            }
        }
    }
    final int status = conn.getResponseCode();
    conn.disconnect();
    return status == HttpURLConnection.HTTP_OK;
}

From source file:com.gmobi.poponews.util.HttpHelper.java

public static Response upload(String url, InputStream is) {
    Response response = new Response();
    String boundary = Long.toHexString(System.currentTimeMillis());
    HttpURLConnection connection = null;
    try {//w w  w .  j  a  v  a  2  s .co m
        URL httpURL = new URL(url);
        connection = (HttpURLConnection) httpURL.openConnection();
        connection.setConnectTimeout(15000);
        connection.setReadTimeout(30000);
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        byte[] st = ("--" + boundary + "\r\n"
                + "Content-Disposition: form-data; name=\"file\"; filename=\"data\"\r\n"
                + "Content-Type: application/octet-stream; charset=UTF-8\r\n"
                + "Content-Transfer-Encoding: binary\r\n\r\n").getBytes();
        byte[] en = ("\r\n--" + boundary + "--\r\n").getBytes();
        connection.setRequestProperty("Content-Length", String.valueOf(st.length + en.length + is.available()));
        OutputStream os = connection.getOutputStream();
        os.write(st);
        FileHelper.copy(is, os);
        os.write(en);
        os.flush();
        os.close();
        response.setStatusCode(connection.getResponseCode());
        connection = null;
    } catch (Exception e) {
        Logger.error(e);
    }

    return response;
}

From source file:com.kotcrab.vis.editor.CrashReporter.java

private void sendReport() {
    progressBox.setVisible(true);//from www . j  a  v  a2  s.  c om

    Task<Void> task = new Task<Void>() {
        @Override
        public Void call() {
            try {
                HttpURLConnection connection = (HttpURLConnection) new URL(
                        REPORT_URL + "?filename=" + reportFile.getName()).openConnection();
                connection.setDoOutput(true);
                connection.setRequestMethod("POST");
                OutputStream os = connection.getOutputStream();

                if (detailsTextArea.getText().equals("") == false) {
                    os.write(("Details: " + detailsTextArea.getText()).getBytes());
                    os.write('\n');
                }
                os.write(report.getBytes());
                os.flush();
                os.close();

                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

                String s;
                while ((s = in.readLine()) != null)
                    System.out.println("Server response: " + s);
                in.close();

                System.out.println("Crash report sent");
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void succeeded() {
            Platform.exit();
        }

        @Override
        protected void failed() {
            Platform.exit();
        }
    };
    new Thread(task).start();
}

From source file:cz.vse.fis.keg.entityclassifier.core.entitylinking.SFISearch.java

public LinkedEntity findWikipediaArticle(String mention, String lang) {

    LinkedEntity linkedEntity = null;/*  w  w w . ja  v a 2s  .c  o m*/
    OutputStream os = null;
    try {
        String url = Settings.SEMITAGS_LINKING_ENDPOINT;
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        String data = "lang=" + lang + "&surfaceForm=" + mention;
        con.setRequestMethod("POST");
        con.setRequestProperty("Accept", "application/json");
        con.setDoOutput(true);
        os = con.getOutputStream();
        os.write(data.getBytes("UTF-8"));
        os.flush();
        os.close();

        int responseCode = con.getResponseCode();

        int code = con.getResponseCode();

        if (code == 500) {
            return linkedEntity;
        }
        StringBuffer buffer = new StringBuffer();
        InputStream is = con.getInputStream();
        Reader isr = new InputStreamReader(is, "UTF-8");
        Reader in = new BufferedReader(isr);
        int ch;
        while ((ch = in.read()) > -1) {
            buffer.append((char) ch);
        }
        in.close();
        isr.close();
        String result = buffer.toString();

        Object linkObj = null;
        Object scoreObj = null;
        String link = "";
        double score;
        JSONObject jsonObj = new JSONObject(result);

        linkObj = jsonObj.get("link");
        scoreObj = jsonObj.get("socre");
        if (!linkObj.toString().equals("null")) {
            link = jsonObj.getString("link");
            score = jsonObj.getDouble("socre");
            linkedEntity = new LinkedEntity();
            linkedEntity.setPageTitle(link.split("/")[link.split("/").length - 1].replace("_", " "));
            linkedEntity.setConfidence(score);
            return linkedEntity;
        } else {
            return null;
        }
    } catch (MalformedURLException ex) {
        Logger.getLogger(SFISearch.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(SFISearch.class.getName()).log(Level.SEVERE, null, ex);
    }

    return linkedEntity;
}

From source file:de.wpsverlinden.otrsspy.OtrsSpy.java

private void login() throws MalformedURLException, IOException, ExtractException {
    logger.info("Login...");
    HttpURLConnection conn = (HttpURLConnection) (new URL(host + "index.pl")).openConnection();
    conn.setRequestMethod("POST");
    conn.setInstanceFollowRedirects(false);
    conn.setDoOutput(true);/*from  www. ja v  a 2 s .c  om*/
    try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
        wr.writeBytes("Action=Login&RequestedURL=&Lang=" + lang + "&TimeOffset=-120&User=" + user + "&Password="
                + password);
        wr.flush();
    }
    session = extractSession(conn);
}

From source file:com.example.appengine.appidentity.UrlShortener.java

/**
 * Returns a shortened URL by calling the Google URL Shortener API.
 *
 * <p>Note: Error handling elided for simplicity.
 *//*from   w ww.  ja v  a  2 s  . c o m*/
public String createShortUrl(String longUrl) throws Exception {
    ArrayList<String> scopes = new ArrayList<String>();
    scopes.add("https://www.googleapis.com/auth/urlshortener");
    final AppIdentityService appIdentity = AppIdentityServiceFactory.getAppIdentityService();
    final AppIdentityService.GetAccessTokenResult accessToken = appIdentity.getAccessToken(scopes);
    // The token asserts the identity reported by appIdentity.getServiceAccountName()
    JSONObject request = new JSONObject();
    request.put("longUrl", longUrl);

    URL url = new URL("https://www.googleapis.com/urlshortener/v1/url?pp=1");
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setRequestMethod("POST");
    connection.addRequestProperty("Content-Type", "application/json");
    connection.addRequestProperty("Authorization", "Bearer " + accessToken.getAccessToken());

    OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
    request.write(writer);
    writer.close();

    if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
        // Note: Should check the content-encoding.
        //       Any JSON parser can be used; this one is used for illustrative purposes.
        JSONTokener responseTokens = new JSONTokener(connection.getInputStream());
        JSONObject response = new JSONObject(responseTokens);
        return (String) response.get("id");
    } else {
        try (InputStream s = connection.getErrorStream();
                InputStreamReader r = new InputStreamReader(s, StandardCharsets.UTF_8)) {
            throw new RuntimeException(String.format("got error (%d) response %s from %s",
                    connection.getResponseCode(), CharStreams.toString(r), connection.toString()));
        }
    }
}