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:it.avalz.opendaylight.controller.Controller.java

public void addFlow(Flow f) {
    Vertex v = f.getNode();/*from  w w w.ja  v a 2  s.c o  m*/

    String authString = this.username + ":" + this.password;

    try {
        StringBuilder urlString = new StringBuilder();

        urlString.append(this.baseUrl).append("/flowprogrammer/default/node/OF/").append(v.getId())
                .append("/staticFlow/").append(f.getName());
        URL url = new URL(urlString.toString());
        byte[] authEncoded = Base64.encodeBase64(authString.getBytes());
        String authEncodedString = new String(authEncoded);

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

        connection.setDoOutput(true);
        connection.setRequestMethod("PUT");

        connection.setRequestProperty("Authorization", "Basic " + authEncodedString);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Accept", "application/json");

        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());

        out.write(f.toString());
        out.close();

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

    System.out.println("Flow installed on vertex " + v);
    System.out.println(f);
}

From source file:com.example.pabrto.AppEngineClient.java

public static Response getOrPost(Request request) {
    mErrorMessage = null;//  w  w  w .j  a  v  a  2  s. c  o m
    HttpURLConnection conn = null;
    Response response = null;
    try {
        conn = (HttpURLConnection) request.uri.openConnection();
        //            if (!mAuthenticator.authenticate(conn)) {
        //                mErrorMessage = str(R.string.aerc_authentication_failed) + ": " + mAuthenticator.errorMessage();
        //            } else 
        {
            if (request.headers != null) {
                for (String header : request.headers.keySet()) {
                    for (String value : request.headers.get(header)) {
                        conn.addRequestProperty(header, value);
                    }
                }
            }
            if (request instanceof POST) {
                byte[] payload = ((POST) request).body;
                String s = new String(payload, "UTF-8");
                conn.setDoOutput(true);
                conn.setDoInput(true);
                conn.setRequestMethod("POST");

                JSONObject jsonobj = getJSONObject(s);

                conn.setRequestProperty("Content-Type", "application/json; charset=utf8");

                // ...

                OutputStream os = conn.getOutputStream();
                os.write(jsonobj.toString().getBytes("UTF-8"));
                os.close();

                //                    conn.setFixedLengthStreamingMode(payload.length);
                //                    conn.getOutputStream().write(payload);
                int status = conn.getResponseCode();
                if (status / 100 != 2)
                    response = new Response(status, new Hashtable<String, List<String>>(),
                            conn.getResponseMessage().getBytes());
            }
            if (response == null) {
                int a = conn.getResponseCode();
                InputStream a1 = conn.getErrorStream();
                BufferedInputStream in = new BufferedInputStream(conn.getInputStream());

                byte[] body = readStream(in);

                response = new Response(conn.getResponseCode(), conn.getHeaderFields(), body);
                //   List<String> a = conn.getHeaderFields().get("aa");
            }
        }
    } catch (IOException e) {
        e.printStackTrace(System.err);
        mErrorMessage = ((request instanceof POST) ? "POST " : "GET ") + str(R.string.aerc_failed) + ": "
                + e.getLocalizedMessage();
    } finally {
        if (conn != null)
            conn.disconnect();
    }
    return response;
}

From source file:com.example.rtobase2.AppEngineClient.java

public static Response getOrPost(Request request) {
    mErrorMessage = null;/* www  .  ja va2s. c o m*/
    HttpURLConnection conn = null;
    Response response = null;
    try {
        conn = (HttpURLConnection) request.uri.openConnection();
        //            if (!mAuthenticator.authenticate(conn)) {
        //                mErrorMessage = str(R.string.aerc_authentication_failed) + ": " + mAuthenticator.errorMessage();
        //            } else 
        {
            if (request.headers != null) {
                for (String header : request.headers.keySet()) {
                    for (String value : request.headers.get(header)) {
                        conn.addRequestProperty(header, value);
                    }
                }
            }

            if (request instanceof PUT) {
                byte[] payload = ((PUT) request).body;
                String s = new String(payload, "UTF-8");
                conn.setDoOutput(true);
                conn.setDoInput(true);

                conn.setRequestMethod("PUT");
                JSONObject jsonobj = getJSONObject(s);
                conn.setRequestProperty("Content-Type", "application/json; charset=utf8");
                OutputStream os = conn.getOutputStream();
                os.write(jsonobj.toString().getBytes("UTF-8"));
                os.close();
            }

            if (request instanceof POST) {
                byte[] payload = ((POST) request).body;
                String s = new String(payload, "UTF-8");
                conn.setDoOutput(true);
                conn.setDoInput(true);
                conn.setRequestMethod("POST");

                JSONObject jsonobj = getJSONObject(s);

                conn.setRequestProperty("Content-Type", "application/json; charset=utf8");

                // ...

                OutputStream os = conn.getOutputStream();
                os.write(jsonobj.toString().getBytes("UTF-8"));
                os.close();

                //                    conn.setFixedLengthStreamingMode(payload.length);
                //                    conn.getOutputStream().write(payload);
                int status = conn.getResponseCode();
                if (status / 100 != 2)
                    response = new Response(status, new Hashtable<String, List<String>>(),
                            conn.getResponseMessage().getBytes());
            }
            if (response == null) {

                BufferedInputStream in = new BufferedInputStream(conn.getInputStream());

                byte[] body = readStream(in);

                response = new Response(conn.getResponseCode(), conn.getHeaderFields(), body);
                //   List<String> a = conn.getHeaderFields().get("aa");
            }
        }
    } catch (IOException e) {
        e.printStackTrace(System.err);
        mErrorMessage = ((request instanceof POST) ? "POST " : "GET ") + str(R.string.aerc_failed) + ": "
                + e.getLocalizedMessage();
    } finally {
        if (conn != null)
            conn.disconnect();
    }
    return response;
}

From source file:net.phalapi.sdk.PhalApiClient.java

protected String doRequest(String requestUrl, Map<String, String> params, int timeoutMs) throws Exception {
    String result = null;/* w  w  w .  j a v a  2 s .co  m*/
    URL url = null;
    HttpURLConnection connection = null;
    InputStreamReader in = null;

    url = new URL(requestUrl);
    connection = (HttpURLConnection) url.openConnection();
    connection.setDoInput(true);
    connection.setDoOutput(true);
    connection.setRequestMethod("POST"); // ?
    connection.setUseCaches(false);
    connection.setConnectTimeout(timeoutMs);

    DataOutputStream out = new DataOutputStream(connection.getOutputStream());

    //POST?
    String postContent = "";
    Iterator<Entry<String, String>> iter = params.entrySet().iterator();
    while (iter.hasNext()) {
        Map.Entry<String, String> entry = (Map.Entry<String, String>) iter.next();
        postContent += "&" + entry.getKey() + "=" + entry.getValue();
    }
    out.writeBytes(postContent);
    out.flush();
    out.close();

    Log.d("[PhalApiClient requestUrl]", requestUrl + postContent);

    in = new InputStreamReader(connection.getInputStream());
    BufferedReader bufferedReader = new BufferedReader(in);
    StringBuffer strBuffer = new StringBuffer();
    String line = null;
    while ((line = bufferedReader.readLine()) != null) {
        strBuffer.append(line);
    }
    result = strBuffer.toString();

    Log.d("[PhalApiClient apiResult]", result);

    if (connection != null) {
        connection.disconnect();
    }

    if (in != null) {
        try {
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return result;
}

From source file:org.openxdata.server.servlet.DataImportServletTest.java

@Test
@Ignore("this is an integration test for localhost")
public void integrationTest() throws Exception {
    final String urlString = "http://localhost:8888/org.openxdata.server.admin.OpenXDataServerAdmin/dataimport?msisdn=2222222";
    final String userName = "dagmar";
    final String password = "dagmar";

    // open url connection
    URL url = new URL(urlString);
    HttpURLConnection con = (HttpURLConnection) url.openConnection();
    con.setRequestMethod("GET");
    con.setDoOutput(true);/*from   www  .j  av  a  2s .co m*/
    con.setDoInput(true);
    con.setChunkedStreamingMode(1024);

    // stuff the Authorization request header
    byte[] encodedPassword = (userName + ":" + password).getBytes();
    con.setRequestProperty("Authorization", "Basic " + new String(Base64.encodeBase64(encodedPassword)));

    // put the form data on the output stream
    DataOutputStream out = new DataOutputStream(con.getOutputStream());
    out.writeByte(new Integer(1));
    String data = "<?xml version='1.0' encoding='UTF-8' ?><cmt_lesotho_tlpp_session_report_v1 formKey=\"cmt_lesotho_tlpp_session_report_v1\" id=\"2\" name=\"Treatment literacy programme_v1\" xmlns:xf=\"http://www.w3.org/2002/xforms\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">  <name>TEEHEE</name>  <session_type>treatment_literacy_session</session_type>  <session_date>2010-04-15</session_date>  <district>berea</district>  <session_location>secondary_school</session_location>  <session_location_other/>  <session_place_name>dsds</session_place_name>  <participant_number_male>1</participant_number_male>  <participant_number_female>2</participant_number_female>  <session_start_time>10:22:00</session_start_time>  <session_finish_time>01:22:00</session_finish_time>  <session_topic>children_HIV_incl_ARVs</session_topic>  <session_topic_other/>  <support_group>false</support_group>  <one_on_one_session>false</one_on_one_session>  <CMT_AV_kit>false</CMT_AV_kit>  <CMT_DVD>false</CMT_DVD>  <CMT_co_facilitator>false</CMT_co_facilitator>  <co_facilitator_name/>  <clinic_hospital_department/>  <clinic_hospital_department_other/>  <clinic_hospital_TV/>  <school_grade>12</school_grade>  <school_CMT_materials>true</school_CMT_materials>  <session_confirmed>true</session_confirmed></cmt_lesotho_tlpp_session_report_v1>";
    out.writeUTF(data);
    out.flush();

    // pull the information back from the URL
    InputStream is = con.getInputStream();
    StringBuffer buf = new StringBuffer();
    int c;
    while ((c = is.read()) != -1) {
        buf.append((char) c);
    }
    con.disconnect();

    // output the information
    System.out.println(buf);
}

From source file:com.hpe.application.automation.tools.rest.RestClient.java

/**
 * Set connection data/*  ww w .  ja  v a2  s  .co  m*/
 */
private void setConnectionData(HttpURLConnection connnection, byte[] bytes) {

    if (bytes != null && bytes.length > 0) {
        connnection.setDoOutput(true);
        try {
            OutputStream out = connnection.getOutputStream();
            out.write(bytes);
            out.flush();
            out.close();
        } catch (Exception cause) {
            throw new SSEException(cause);
        }
    }
}

From source file:com.streamsets.pipeline.stage.origin.httpserver.TestHttpServerPushSource.java

@Test
public void testSource() throws Exception {
    RawHttpConfigs httpConfigs = new RawHttpConfigs();
    httpConfigs.appId = () -> "id";
    httpConfigs.port = NetworkUtils.getRandomPort();
    httpConfigs.maxConcurrentRequests = 1;
    httpConfigs.tlsConfigBean.tlsEnabled = false;
    HttpServerPushSource source = new HttpServerPushSource(httpConfigs, 1, DataFormat.TEXT,
            new DataParserFormatConfig());
    final PushSourceRunner runner = new PushSourceRunner.Builder(HttpServerDPushSource.class, source)
            .addOutputLane("a").build();
    runner.runInit();//from  w w w.j  a  v  a 2  s .c om
    try {
        final List<Record> records = new ArrayList<>();
        runner.runProduce(Collections.<String, String>emptyMap(), 1, new PushSourceRunner.Callback() {
            @Override
            public void processBatch(StageRunner.Output output) {
                records.clear();
                records.addAll(output.getRecords().get("a"));
            }
        });

        // wait for the HTTP server up and running
        HttpReceiverServer httpServer = (HttpReceiverServer) Whitebox.getInternalState(source, "server");
        await().atMost(Duration.TEN_SECONDS).until(isServerRunning(httpServer));

        HttpURLConnection connection = (HttpURLConnection) new URL("http://localhost:" + httpConfigs.getPort())
                .openConnection();
        connection.setRequestMethod("POST");
        connection.setUseCaches(false);
        connection.setDoOutput(true);
        connection.setRequestProperty(Constants.X_SDC_APPLICATION_ID_HEADER, "id");
        connection.setRequestProperty("customHeader", "customHeaderValue");
        connection.getOutputStream().write("Hello".getBytes());
        Assert.assertEquals(HttpURLConnection.HTTP_OK, connection.getResponseCode());
        Assert.assertEquals(1, records.size());
        Assert.assertEquals("Hello", records.get(0).get("/text").getValue());
        Assert.assertEquals("id",
                records.get(0).getHeader().getAttribute(Constants.X_SDC_APPLICATION_ID_HEADER));
        Assert.assertEquals("customHeaderValue", records.get(0).getHeader().getAttribute("customHeader"));

        // passing App Id via query param should fail when appIdViaQueryParamAllowed is false
        String url = "http://localhost:" + httpConfigs.getPort() + "?"
                + HttpConstants.SDC_APPLICATION_ID_QUERY_PARAM + "=id";
        Response response = ClientBuilder.newClient().target(url).request().post(Entity.json("Hello"));
        Assert.assertEquals(HttpURLConnection.HTTP_FORBIDDEN, response.getStatus());

        runner.setStop();
    } catch (Exception e) {
        Assert.fail(e.getMessage());
    } finally {
        runner.runDestroy();
    }
}

From source file:jeeves.utils.Xml.java

/**
 * Loads an xml file from a URL after posting content to the URL.
 *
 * @param url//from  w  ww.j  a v  a2s. com
 * @param xmlQuery
 * @return
 * @throws IOException
 * @throws JDOMException
 */
public static Element loadFile(URL url, Element xmlQuery) throws IOException, JDOMException {
    Element result = null;
    try {
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/xml");
        connection.setRequestProperty("Content-Length",
                "" + Integer.toString(getString(xmlQuery).getBytes("UTF-8").length));
        connection.setRequestProperty("Content-Language", "en-US");
        connection.setDoOutput(true);
        PrintStream out = new PrintStream(connection.getOutputStream(), true, "UTF-8");
        out.print(getString(xmlQuery));
        out.close();

        SAXBuilder builder = getSAXBuilderWithoutXMLResolver(false);//new SAXBuilder();
        Document jdoc = builder.build(connection.getInputStream());

        result = (Element) jdoc.getRootElement().detach();
    } catch (Exception e) {
        Log.error(Log.ENGINE, "Error loading URL " + url.getPath() + " .Threw exception " + e);
        e.printStackTrace();
    }
    return result;
}

From source file:com.hortonworks.registries.auth.client.AuthenticatorTestCase.java

protected void _testAuthentication(Authenticator authenticator, boolean doPost) throws Exception {
    start();//  w  w w .  j a  va  2s  .c  o m
    try {
        URL url = new URL(getBaseURL());
        AuthenticatedURL.Token token = new AuthenticatedURL.Token();
        Assert.assertFalse(token.isSet());
        TestConnectionConfigurator connConf = new TestConnectionConfigurator();
        AuthenticatedURL aUrl = new AuthenticatedURL(authenticator, connConf);
        HttpURLConnection conn = aUrl.openConnection(url, token);
        Assert.assertTrue(connConf.invoked);
        String tokenStr = token.toString();
        if (doPost) {
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
        }
        conn.connect();
        if (doPost) {
            Writer writer = new OutputStreamWriter(conn.getOutputStream());
            writer.write(POST);
            writer.close();
        }
        Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
        if (doPost) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String echo = reader.readLine();
            Assert.assertEquals(POST, echo);
            Assert.assertNull(reader.readLine());
        }
        aUrl = new AuthenticatedURL();
        conn = aUrl.openConnection(url, token);
        conn.connect();
        Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
        Assert.assertEquals(tokenStr, token.toString());
    } finally {
        stop();
    }
}

From source file:com.windigo.http.client.HttpUrlConnectionClient.java

/**
 * Setup {@link HttpURLConnection} to remote url set some configuration and
 * body if exist//from   w  ww. j a  va 2  s.  co m
 * 
 * @param request
 * @throws MalformedURLException
 * @throws IOException
 */
private void setupHttpUrlConnectionClient(HttpURLConnection connection, Request request)
        throws MalformedURLException, IOException {

    connection.setDoInput(true);

    // set headers for request
    Logger.log("[Request] Found " + request.getHeaders().size() + " header");
    addHeaders(request.getHeaders());

    if (request.hasBody()) {
        // if its post request
        connection.setDoOutput(true);
        OutputStream os = connection.getOutputStream();
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        bw.write(writeBodyParams(request.getBodyParams()));

        // clean up mess
        bw.flush();
        bw.close();
        os.close();
    }

}