Example usage for java.net URLConnection getOutputStream

List of usage examples for java.net URLConnection getOutputStream

Introduction

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

Prototype

public OutputStream getOutputStream() throws IOException 

Source Link

Document

Returns an output stream that writes to this connection.

Usage

From source file:com.zhonghui.tool.controller.HttpClient.java

/**
 * HTTP Post???/*from  w w  w.java2s .c  o  m*/
 *
 * @param connection 
 * @param message ???
 * @throws IOException
 */
private void requestServer(final URLConnection connection, String message, String encoder) throws Exception {
    PrintStream out = null;
    try {
        connection.connect();
        out = new PrintStream(connection.getOutputStream(), false, encoder);
        out.print(message);
        out.flush();
    } catch (Exception e) {
        throw e;
    } finally {
        if (null != out) {
            out.close();
        }
    }
}

From source file:net.sf.jabref.logic.net.URLDownload.java

private URLConnection openConnection() throws IOException {
    URLConnection connection = source.openConnection();
    for (Map.Entry<String, String> entry : parameters.entrySet()) {
        connection.setRequestProperty(entry.getKey(), entry.getValue());
    }//  w  ww. ja v  a 2  s  . co m
    if (!postData.isEmpty()) {
        connection.setDoOutput(true);
        try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
            wr.writeBytes(postData);
        }

    }
    // this does network i/o: GET + read returned headers
    connection.connect();

    return connection;
}

From source file:org.wso2.esb.integration.common.utils.clients.JSONClient.java

private JSONObject sendRequest(String addUrl, String query, String action) throws IOException, JSONException {
    String charset = "UTF-8";
    URLConnection connection = new URL(addUrl).openConnection();
    connection.setDoOutput(true);/*from  w  w w.j a  v  a2s  . c  om*/
    connection.setRequestProperty("Accept-Charset", charset);
    connection.setRequestProperty("SOAPAction", action);
    connection.setRequestProperty("Content-Type", "application/json;charset=" + charset);
    OutputStream output = null;
    try {
        output = connection.getOutputStream();
        output.write(query.getBytes(charset));
    } finally {
        if (output != null) {
            try {
                output.close();
            } catch (IOException logOrIgnore) {
                log.error("Error while closing the connection");
            }
        }
    }
    InputStream response = connection.getInputStream();
    String out = "[Fault] No Response.";
    if (response != null) {
        StringBuilder sb = new StringBuilder();
        byte[] bytes = new byte[1024];
        int len;
        while ((len = response.read(bytes)) != -1) {
            sb.append(new String(bytes, 0, len));
        }
        out = sb.toString();
    }

    JSONObject jsonObject = new JSONObject(out);

    return jsonObject;
}

From source file:org.apache.servicemix.jbi.itests.IntegrationTest.java

@Test
public void testServiceAssembly() throws Throwable {
    System.out.println("Waiting for NMR");
    NMR nmr = getOsgiService(NMR.class);
    assertNotNull(nmr);/*from   w w  w . jav  a2s  . com*/

    Bundle smxShared = installJbiBundle("org.apache.servicemix", "servicemix-shared", "installer", "zip");
    Bundle smxJsr181 = installJbiBundle("org.apache.servicemix", "servicemix-jsr181", "installer", "zip");
    Bundle smxHttp = installJbiBundle("org.apache.servicemix", "servicemix-http", "installer", "zip");
    Bundle saBundle = installJbiBundle("org.apache.servicemix.samples.wsdl-first", "wsdl-first-sa", null,
            "zip");

    smxShared.start();
    smxJsr181.start();
    smxHttp.start();
    saBundle.start();

    System.out.println("Waiting for JBI Service Assembly");
    ServiceAssembly sa = getOsgiService(ServiceAssembly.class);
    assertNotNull(sa);

    Thread.sleep(500);

    final List<Throwable> errors = new CopyOnWriteArrayList<Throwable>();
    final int nbThreads = 2;
    final int nbMessagesPerThread = 10;
    final CountDownLatch latch = new CountDownLatch(nbThreads * nbMessagesPerThread);
    for (int i = 0; i < nbThreads; i++) {
        new Thread() {
            public void run() {
                for (int i = 0; i < nbMessagesPerThread; i++) {
                    try {
                        URL url = new URL("http://localhost:8192/PersonService/");
                        URLConnection connection = url.openConnection();
                        connection.setDoInput(true);
                        connection.setDoOutput(true);
                        connection.getOutputStream().write(
                                ("<env:Envelope xmlns:env=\"http://schemas.xmlsoap.org/soap/envelope/\"\n"
                                        + "              xmlns:tns=\"http://servicemix.apache.org/samples/wsdl-first/types\">\n"
                                        + "  <env:Body>\n" + "    <tns:GetPerson>\n"
                                        + "      <tns:personId>world</tns:personId>\n"
                                        + "    </tns:GetPerson>\n" + "  </env:Body>\n" + "</env:Envelope>")
                                                .getBytes());
                        byte[] buffer = new byte[8192];
                        int len = connection.getInputStream().read(buffer);
                        if (len == -1) {
                            throw new Exception("No response available");
                        }
                        String result = new String(buffer, 0, len);
                        System.out.println(result);
                    } catch (Throwable t) {
                        errors.add(t);
                        t.printStackTrace();
                    } finally {
                        latch.countDown();
                    }
                }
            }
        }.start();
    }

    if (!latch.await(60, TimeUnit.SECONDS)) {
        fail("Test timed out");
    }
    if (!errors.isEmpty()) {
        throw errors.get(0);
    }
    //Thread.sleep(500);
    saBundle.uninstall();
    //sa.stop();
    //sa.shutDown();
}

From source file:org.apache.ode.jbi.JbiTestBase.java

protected void go() throws Exception {
    boolean manualDeploy = Boolean.parseBoolean("" + testProperties.getProperty("manualDeploy"));
    if (!manualDeploy)
        enableProcess(getTestName(), true);

    try {//from w w  w  .ja v a  2s .co m
        int i = 0;
        boolean loop;
        do {
            String prefix = i == 0 ? "" : "" + i;
            loop = i == 0;

            {
                String deploy = testProperties.getProperty(prefix + "deploy");
                if (deploy != null) {
                    loop = true;
                    enableProcess(getTestName() + "/" + deploy, true);
                }
            }
            {
                String undeploy = testProperties.getProperty(prefix + "undeploy");
                if (undeploy != null) {
                    loop = true;
                    enableProcess(getTestName() + "/" + undeploy, false);
                }
            }

            String request = testProperties.getProperty(prefix + "request");
            if (request != null && request.startsWith("@")) {
                request = inputStreamToString(
                        getClass().getResourceAsStream("/" + getTestName() + "/" + request.substring(1)));
            }
            String expectedResponse = testProperties.getProperty(prefix + "response");
            {
                String delay = testProperties.getProperty(prefix + "delay");
                if (delay != null) {
                    loop = true;
                    long d = Long.parseLong(delay);
                    log.debug("Sleeping " + d + " ms");
                    Thread.sleep(d);
                }
            }
            {
                String httpUrl = testProperties.getProperty(prefix + "http.url");
                if (httpUrl != null && request != null) {
                    loop = true;
                    log.debug(getTestName() + " sending http request to " + httpUrl + " request: " + request);
                    URLConnection connection = new URL(httpUrl).openConnection();
                    connection.setDoOutput(true);
                    connection.setDoInput(true);
                    //Send request
                    OutputStream os = connection.getOutputStream();
                    PrintWriter wt = new PrintWriter(os);
                    wt.print(request);
                    wt.flush();
                    wt.close();
                    // Read the response.
                    String result = inputStreamToString(connection.getInputStream());

                    log.debug(getTestName() + " have result: " + result);
                    matchResponse(expectedResponse, result, true);
                }
            }
            {
                if (testProperties.getProperty(prefix + "nmr.service") != null && request != null) {
                    loop = true;
                    InOut io = smxClient.createInOutExchange();
                    io.setService(QName.valueOf(testProperties.getProperty(prefix + "nmr.service")));
                    io.setOperation(QName.valueOf(testProperties.getProperty(prefix + "nmr.operation")));
                    io.getInMessage()
                            .setContent(new StreamSource(new ByteArrayInputStream(request.getBytes())));
                    smxClient.sendSync(io, 20000);
                    if (io.getStatus() == ExchangeStatus.ACTIVE) {
                        assertNotNull(io.getOutMessage());
                        String result = new SourceTransformer().contentToString(io.getOutMessage());
                        matchResponse(expectedResponse, result, true);
                        smxClient.done(io);
                    } else {
                        matchResponse(expectedResponse, "", false);
                    }
                }
            }

            i++;
        } while (loop);

    } finally {
        if (!manualDeploy)
            enableProcess(getTestName(), false);
    }
}

From source file:org.apache.roller.weblogger.ui.rendering.plugins.comments.AkismetCommentValidator.java

public int validate(WeblogEntryComment comment, RollerMessages messages) {
    StringBuffer sb = new StringBuffer();
    sb.append("blog=").append(WebloggerFactory.getWeblogger().getUrlStrategy()
            .getWeblogURL(comment.getWeblogEntry().getWebsite(), null, true)).append("&");
    sb.append("user_ip=").append(comment.getRemoteHost()).append("&");
    sb.append("user_agent=").append(comment.getUserAgent()).append("&");
    sb.append("referrer=").append(comment.getReferrer()).append("&");
    sb.append("permalink=").append(comment.getWeblogEntry().getPermalink()).append("&");
    sb.append("comment_type=").append("comment").append("&");
    sb.append("comment_author=").append(comment.getName()).append("&");
    sb.append("comment_author_email=").append(comment.getEmail()).append("&");
    sb.append("comment_author_url=").append(comment.getUrl()).append("&");
    sb.append("comment_content=").append(comment.getContent());

    try {/* w  w w  .  jav  a  2  s . c  om*/
        URL url = new URL("http://" + apikey + ".rest.akismet.com/1.1/comment-check");
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);

        conn.setRequestProperty("User_Agent", "Roller " + WebloggerFactory.getWeblogger().getVersion());
        conn.setRequestProperty("Content-type", "application/x-www-form-urlencoded;charset=utf8");
        conn.setRequestProperty("Content-length", Integer.toString(sb.length()));

        OutputStreamWriter osr = new OutputStreamWriter(conn.getOutputStream());
        osr.write(sb.toString(), 0, sb.length());
        osr.flush();
        osr.close();

        BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String response = br.readLine();
        if ("true".equals(response)) {
            messages.addError("comment.validator.akismetMessage");
            return 0;
        } else
            return 100;
    } catch (Exception e) {
        log.error("ERROR checking comment against Akismet", e);
    }
    return 0; // interpret error as spam: better safe than sorry? 
}

From source file:BihuHttpUtil.java

/**
 * ? URL ??POST//  w  ww.  j  av  a2  s . c o  m
 *
 * @param url
 *               ?? URL
 * @param param
 *               ?? name1=value1&name2=value2 ?
 * @param sessionId
 *             ???
 * @return ??
 */
public static Map<String, String> sendPost(String url, String param, String sessionId) {
    Map<String, String> resultMap = new HashMap<String, String>();
    PrintWriter out = null;
    BufferedReader in = null;
    String result = "";
    try {
        URL realUrl = new URL(url);
        // URL
        URLConnection conn = realUrl.openConnection();
        // 
        //conn.setRequestProperty("Host", "quote.zhonghe-bj.com:8085");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        conn.setRequestProperty("Accept", "*/*");
        conn.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");
        conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
        if (StringUtils.isNotBlank(sessionId)) {
            conn.setRequestProperty("Cookie", sessionId);
        }
        // ??POST
        conn.setDoOutput(true);
        conn.setDoInput(true);
        // ?URLConnection?
        out = new PrintWriter(conn.getOutputStream());
        // ???
        out.print(param);
        // flush?
        out.flush();
        // BufferedReader???URL?
        in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String cookieValue = conn.getHeaderField("Set-Cookie");
        resultMap.put("cookieValue", cookieValue);
        String line;
        while ((line = in.readLine()) != null) {
            result += line;
        }
    } catch (Exception e) {
        System.out.println("?? POST ?" + e);
        e.printStackTrace();
    }
    // finally?????
    finally {
        try {
            if (out != null) {
                out.close();
            }
            if (in != null) {
                in.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    resultMap.put("result", result);
    return resultMap;
}

From source file:com.entertailion.android.shapeways.api.ShapewaysClient.java

/**
 * Get the request token/*from   w w w  . j  a  v a 2 s.  c om*/
 * 
 * @param callbackUrl
 *            HTTP callback URL for handling the user authorization
 * @return
 * @throws Exception
 */
public Map<String, String> getRequestToken(String callbackUrl) throws Exception {
    Log.d(LOG_TAG, "getRequestToken");
    URLConnection urlConnection = getUrlConnection(API_URL_BASE + REQUEST_TOKEN_PATH, true);

    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(urlConnection.getOutputStream());

    Request request = new Request(POST);
    request.addParameter(OAUTH_CONSUMER_KEY, consumerKey);
    request.addParameter(OAUTH_CALLBACK, callbackUrl);
    request.sign(API_URL_BASE + REQUEST_TOKEN_PATH, consumerSecret, null);
    outputStreamWriter.write(request.toString());
    outputStreamWriter.close();

    return readParams(urlConnection.getInputStream());
}

From source file:com.entertailion.android.shapeways.api.ShapewaysClient.java

/**
 * Get the access token//from   w  w  w  .j  av a2 s.  c  o  m
 * 
 * @param requestToken
 * @param requestTokenSecret
 * @param requestTokenVerifier
 * @return
 * @throws Exception
 */
public Map<String, String> getAccessToken(String requestToken, String requestTokenSecret,
        String requestTokenVerifier) throws Exception {
    Log.d(LOG_TAG, "getAccessToken");
    URLConnection urlConnection = getUrlConnection(API_URL_BASE + ACCESS_TOKEN_PATH, true);

    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(urlConnection.getOutputStream());

    Request request = new Request(POST);
    request.addParameter(OAUTH_CONSUMER_KEY, consumerKey);
    request.addParameter(OAUTH_TOKEN, requestToken);
    request.addParameter(OAUTH_VERIFIER, requestTokenVerifier);
    request.sign(API_URL_BASE + ACCESS_TOKEN_PATH, consumerSecret, requestTokenSecret);
    outputStreamWriter.write(request.toString());
    outputStreamWriter.close();

    return readParams(urlConnection.getInputStream());
}

From source file:africastalkinggateway.AfricasTalkingGateway.java

private String sendPOSTRequest(HashMap<String, String> dataMap_, String urlString_) throws Exception {
    try {/*from   ww w.j a v a  2  s .co  m*/
        String data = new String();
        Iterator<Entry<String, String>> it = dataMap_.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, String> pairs = (Map.Entry<String, String>) it.next();
            data += URLEncoder.encode(pairs.getKey().toString(), "UTF-8");
            data += "=" + URLEncoder.encode(pairs.getValue().toString(), "UTF-8");
            if (it.hasNext())
                data += "&";
        }
        URL url = new URL(urlString_);
        URLConnection conn = url.openConnection();
        conn.setRequestProperty("Accept", "application/json");
        conn.setRequestProperty("apikey", _apiKey);
        conn.setDoOutput(true);
        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
        writer.write(data);
        writer.flush();

        HttpURLConnection http_conn = (HttpURLConnection) conn;
        responseCode = http_conn.getResponseCode();

        BufferedReader reader;
        if (responseCode == HTTP_CODE_OK || responseCode == HTTP_CODE_CREATED)
            reader = new BufferedReader(new InputStreamReader(http_conn.getInputStream()));
        else
            reader = new BufferedReader(new InputStreamReader(http_conn.getErrorStream()));
        String response = reader.readLine();

        if (DEBUG)
            System.out.println(response);

        reader.close();
        return response;

    } catch (Exception e) {
        throw e;
    }
}