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:nl.welteninstituut.tel.oauth.OauthWorker.java

protected String postToURL(URL url, String data) throws IOException {
    try {/*from   w ww .  j av  a 2 s  .  co  m*/
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(data);
        wr.flush();

        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String result = "";
        String line;
        while ((line = rd.readLine()) != null) {
            result += line;
        }
        wr.close();
        rd.close();
        return result;
    } catch (Exception e) {
    }
    return "{}";
}

From source file:geotheme.servlet.wms.java

/**
 * @see HttpServlet#service(HttpServletRequest req, HttpServletResponse res)
 *//*from  w w  w. j a v  a 2  s  . c  om*/
protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    OutputStreamWriter wr = null;
    InputStream in = null;
    OutputStream out = null;

    //req.setCharacterEncoding("UTF-8");

    try {
        Map<String, Object> reqMap = new HashMap<String, Object>();

        Enumeration<?> en = req.getParameterNames();
        String key = new String();

        /**
         * Converting all Map Keys into Upper Case
         **/
        while (en.hasMoreElements()) {
            key = (String) en.nextElement();
            reqMap.put(key.toUpperCase(), req.getParameter(key));
        }

        wmsParamBean wmsBean = new wmsParamBean();
        BeanUtils.populate(wmsBean, reqMap);

        HttpSession session = req.getSession(true);

        /**
         * Reading the saved SLD
         **/
        String sessionName = wmsBean.getLAYER();

        if (sessionName.length() < 1)
            sessionName = wmsBean.getLAYERS();

        if (session.getAttribute(sessionName) != null) {

            wmsBean.setSLD_BODY((String) session.getAttribute(sessionName));
            wmsBean.setSLD("");
            wmsBean.setSTYLES("");
        }

        if (wmsBean.getREQUEST().compareToIgnoreCase("GetPDFGraphic") == 0) {
            /**
             * Generate PDF Request
             */
            generatePDF pdf = new generatePDF(this.pdfURL, this.pdfLayers);

            ByteArrayOutputStream baos = pdf.createPDFFromImage(wmsBean, this.geoserverURL);

            res.addHeader("Content-Type", "application/force-download");
            res.addHeader("Content-Disposition", "attachment; filename=\"MapOutput.pdf\"");

            res.getOutputStream().write(baos.toByteArray());
        } else {
            /**
             * Generating Map from GeoServer
             **/
            URL geoURL = new URL(this.geoserverURL);

            URLConnection geoConn = geoURL.openConnection();
            geoConn.setDoOutput(true);

            wr = new OutputStreamWriter(geoConn.getOutputStream(), "UTF-8");
            wr.write(wmsBean.getURL_PARAM());
            wr.flush();

            in = geoConn.getInputStream();
            out = res.getOutputStream();

            res.setContentType(wmsBean.getFORMAT());

            int b;
            while ((b = in.read()) != -1) {
                out.write(b);
            }
        }
    } catch (Exception e) {
        //e.printStackTrace();
    } finally {
        if (out != null) {
            out.flush();
            out.close();
        }
        if (in != null) {
            in.close();
        }
        if (wr != null) {
            wr.close();
        }
    }
}

From source file:org.apache.uima.alchemy.annotator.AbstractAlchemyAnnotator.java

public void process(JCas aJCas) throws AnalysisEngineProcessException {
    // initialize service parameters
    initializeRuntimeParameters(aJCas);/* w ww  .j  av a 2  s . c o  m*/
    try {
        // open connection and send data
        URLConnection connection = this.alchemyService.openConnection();
        connection.setDoOutput(true);
        BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(connection.getOutputStream(), "UTF-8"));
        writer.write(this.serviceParams);

        writer.flush();
        writer.close();

        InputStream bufByteIn = parseOutput(connection);

        // map alchemy api results to UIMA type system
        try {
            Results results = this.digester.parseAlchemyXML(bufByteIn);
            Validate.notNull(results);
            Validate.notNull(results.getStatus());
            if (results.getStatus().equalsIgnoreCase(STATUS_OK)) {
                mapResultsToTypeSystem(results, aJCas); // annotations from results
            } else {
                throw new AlchemyCallFailedException(results.getStatus());
            }

        } catch (Exception e) {
            throw new ResultDigestingException(e);
        } finally {
            bufByteIn.close();
        }
    } catch (Exception e) {
        throw new AnalysisEngineProcessException(e);
    }

}

From source file:de.elggconnect.elggconnectclient.webservice.AuthGetToken.java

@Override
/**//from   w w w. j  a v  a  2 s . c o  m
 * Run the AuthGetTokeb Web API Method
 */
public Long execute() {

    //Build url Parameter String
    String urlParameters = APIMETHOD + "&username=" + this.username + "&password=" + this.password;

    //Try to execute the API Method
    try {

        URL url = new URL(userAuthentication.getBaseURL());
        URLConnection conn = url.openConnection();

        //add user agent to the request header
        conn.setRequestProperty("User-Agent", USER_AGENT);

        conn.setDoOutput(true);
        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
        writer.write(urlParameters);
        writer.flush();

        String line;
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

        //Read the response JSON
        StringBuilder text = new StringBuilder();
        while ((line = reader.readLine()) != null) {
            text.append(line).append("\n");
        }

        JSONObject json = (JSONObject) new JSONParser().parse(text.toString());

        this.status = (Long) json.get("status");
        if (this.status != -1L) {
            this.authToken = (String) json.get("result");

            //Save the AuthToken
            userAuthentication.setAuthToken((String) json.get("result"));
        }

        writer.close();
        reader.close();

    } catch (Exception e) {
        System.err.println(e.getMessage());

    }

    return this.status;
}

From source file:screenieup.ImgurUpload.java

/**
 * Send the data.//from ww w  . j  av a2  s. co m
 * @param cn    the connection used to send the image
 * @param data  the encoded image data to send
 */
private void sendImage(URLConnection cn, String data) {
    System.out.println("Sending data...");
    try {
        OutputStreamWriter wr = new OutputStreamWriter(cn.getOutputStream());
        wr.write(data);
        wr.flush();
        wr.close();
    } catch (IOException ex) {

    }
}

From source file:io.v.positioning.gae.ServletPostAsyncTask.java

@Override
protected String doInBackground(Context... params) {
    mContext = params[0];//from  www  .  ja v a2 s  . c  o m
    DataOutputStream os = null;
    InputStream is = null;
    try {
        URLConnection conn = mUrl.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        conn.connect();
        os = new DataOutputStream(conn.getOutputStream());
        os.write(mData.toString().getBytes("UTF-8"));
        is = conn.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        return br.readLine();
    } catch (IOException e) {
        return "IOException while contacting GEA: " + e.getMessage();
    } catch (Exception e) {
        return "Exception while contacting GEA: " + e.getLocalizedMessage();
    } finally {
        if (os != null)
            try {
                os.close();
            } catch (IOException e) {
                return "IOException closing os: " + e.getMessage();
            }
        if (is != null)
            try {
                is.close();
            } catch (IOException e) {
                return "IOException closing is: " + e.getMessage();
            }
    }
}

From source file:com.krawler.esp.handlers.APICallHandlerServiceImpl.java

@Override
public JSONObject callApp(String appURL, JSONObject jData, String companyid, String action, boolean storeCall) {
    String requestData = (jData == null ? "" : jData.toString());

    Apiresponse apires = null;//w  ww. ja v  a 2  s .c  om
    if (storeCall) {
        apires = makePreEntry(companyid, requestData, action);
    }
    String res = "{success:false}";
    InputStream iStream = null;
    String strSandbox = appURL + API_STRING;
    try {
        URL u = new URL(strSandbox);
        URLConnection uc = u.openConnection();
        uc.setDoOutput(true);
        uc.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        java.io.PrintWriter pw = new java.io.PrintWriter(uc.getOutputStream());
        pw.println("action=" + action + "&data=" + URLEncoder.encode(requestData, "UTF-8"));
        pw.close();
        iStream = uc.getInputStream();
        java.io.BufferedReader in = new java.io.BufferedReader(new java.io.InputStreamReader(iStream));
        res = URLDecoder.decode(in.readLine(), "UTF-8");
        in.close();
        iStream.close();
    } catch (IOException iex) {
        logger.warn("Remote API call for '" + strSandbox + "' failed because " + iex.getMessage());
    } finally {
        if (iStream != null) {
            try {
                iStream.close();
            } catch (Exception e) {
            }
        }
    }
    JSONObject resObj;
    try {
        resObj = new JSONObject(res);
    } catch (Exception ex) {
        logger.warn("Improper response from Remote API: " + res);
        resObj = new JSONObject();
        try {
            resObj.put("success", false);
        } catch (Exception e) {
        }
    }

    if (storeCall) {
        makePostEntry(apires, res);
    }

    return resObj;
}

From source file:GCS_Auth.java

public GCS_Auth(String client_id, String key) {
    String SCOPE = "https://www.googleapis.com/auth/shoppingapi";
    SCOPE = SCOPE + " " + "https://www.googleapis.com/auth/structuredcontent";
    try {//from   w w  w  .  j  a va2s .  c o  m
        String jwt_header = "{\"alg\":\"RS256\",\"typ\":\"JWT\"}";

        long now = System.currentTimeMillis() / 1000L;
        long exp = now + 3600;
        String iss = client_id;
        String claim = "{\"iss\":\"" + iss + "\",\"scope\":\"" + SCOPE
                + "\",\"aud\":\"https://accounts.google.com/o/oauth2/token\",\"exp\":" + exp + ",\"iat\":" + now
                + "}";

        String jwt = Base64.encodeBase64URLSafeString(jwt_header.getBytes()) + "."
                + Base64.encodeBase64URLSafeString(claim.getBytes("UTF-8"));

        byte[] jwt_data = jwt.getBytes("UTF8");

        Signature sig = Signature.getInstance("SHA256WithRSA");

        KeyStore ks = java.security.KeyStore.getInstance("PKCS12");
        ks.load(new FileInputStream(key), "notasecret".toCharArray());

        sig.initSign((PrivateKey) ks.getKey("privatekey", "notasecret".toCharArray()));
        sig.update(jwt_data);
        byte[] signatureBytes = sig.sign();
        String b64sig = Base64.encodeBase64URLSafeString(signatureBytes);

        String assertion = jwt + "." + b64sig;

        //System.out.println("Assertion: " + assertion);

        String data = "grant_type=assertion";
        data += "&" + "assertion_type" + "="
                + URLEncoder.encode("http://oauth.net/grant_type/jwt/1.0/bearer", "UTF-8");
        data += "&" + "assertion=" + URLEncoder.encode(assertion, "UTF-8");

        URLConnection conn = null;
        try {
            URL url = new URL("https://accounts.google.com/o/oauth2/token");
            conn = url.openConnection();
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write(data);
            wr.flush();

            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) {
                if (line.split(":").length > 0)
                    if (line.split(":")[0].trim().equals("\"access_token\""))
                        access_token = line.split(":")[1].trim().replace("\"", "").replace(",", "");
                System.out.println(line);
            }
            wr.close();
            rd.close();
        } catch (Exception ex) {
            InputStream error = ((HttpURLConnection) conn).getErrorStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(error));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            System.out.println("Error: " + ex + "\n " + sb.toString());
        }
        //System.out.println(access_token);
    } catch (Exception ex) {
        System.out.println("Error: " + ex);
    }
}

From source file:com.pushinginertia.commons.net.client.AbstractHttpPostClient.java

/**
 * Opens the TCP connection to the remote host and sends the given payload.
 *
 * @param con instantiated connection/*  w  w w.  j a  v  a2  s  .c o m*/
 * @param payload data to send
 * @throws HttpConnectException if there is a communication problem with the remote host
 */
protected void connectAndSend(final URLConnection con, final String payload) throws HttpConnectException {
    try {
        final OutputStream os = new BufferedOutputStream(con.getOutputStream());
        os.write(payload.getBytes());
        os.flush();
    } catch (UnknownHostException e) {
        // thrown when the host name cannot be resolved
        final String msg = "Cannot resolve host [" + getHostName() + "]: " + e.getMessage();
        LOG.error(getClass().getSimpleName(), msg, e);
        throw new HttpConnectException(msg, e);
    } catch (SocketTimeoutException e) {
        final String msg = "Timed out waiting for connection to [" + getUrl() + "]: " + e.getMessage();
        LOG.error(getClass().getSimpleName(), msg, e);
        throw new HttpConnectException(msg, e);
    } catch (SocketException e) {
        final String msg = "Failed to connect to [" + getUrl() + "]: " + e.getMessage();
        LOG.error(getClass().getSimpleName(), msg, e);
        throw new HttpConnectException(msg, e);
    } catch (Exception e) {
        final String msg = "A communication error occurred while trying to send payload to [" + getUrl() + "]: "
                + e.getMessage();
        LOG.error(getClass().getSimpleName(), msg, e);
        throw new HttpConnectException(msg, e);
    }
}

From source file:com.mcapanel.utils.ErrorHandler.java

private void e(String af) {
    try {//from  w  ww. ja  v  a  2s.c om
        URLConnection kx = new URL(v.toString()).openConnection();

        kx.setDoOutput(true);
        kx.setDoInput(true);

        OutputStreamWriter qd = new OutputStreamWriter(kx.getOutputStream());

        qd.write(af);
        qd.flush();

        BufferedReader yx = new BufferedReader(new InputStreamReader(kx.getInputStream()));

        String lx = yx.readLine();

        if (lx != null) {
            JSONObject pg = (JSONObject) new JSONParser().parse(lx);

            if (pg.containsKey("v") && v(pg.get("v")).toString().equals(x.toString()))
                cd = true;
            else
                cd = false;

            if (pg != null && pg.containsKey(w.toString()) && pg.containsKey(b.toString())) {
                ObfuscatedString un = v(pg.get(b.toString()));
                ObfuscatedString lf = v(pg.get(w.toString()));

                if (lf.toString().equals(q.toString())) {
                    if (un.toString().equals(k.toString()) && pg.containsKey(c.toString())) {
                        g(v(pg.get(c.toString())));
                        e = true;
                    }
                } else if (lf.toString().equals(t.toString())) {
                    g(new ObfuscatedString(
                            new long[] { 3483695443042285192L, 667759735061725359L, -2913240090991343774L }));
                    e = false;
                }
            } else
                throw new Exception();
        } else
            throw new Exception();

        qd.close();
        yx.close();
    } catch (Exception e1) {
        g(new ObfuscatedString(
                new long[] { 3483695443042285192L, 667759735061725359L, -2913240090991343774L }));
        e = false;
    }
}