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:edu.ucsb.nceas.metacat.util.RequestUtil.java

public static String get(String urlString, Hashtable<String, String[]> params) throws MetacatUtilException {
    try {/*from   w ww .  j  a  va 2 s . c om*/
        URL url = new URL(urlString);
        URLConnection urlConn = url.openConnection();

        urlConn.setDoOutput(true);

        PrintWriter pw = new PrintWriter(urlConn.getOutputStream());
        String queryString = paramsToQuery(params);
        logMetacat.debug("Sending get request: " + urlString + "?" + queryString);
        pw.print(queryString);
        pw.close();

        // get the input from the request
        BufferedReader in = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));

        StringBuffer sb = new StringBuffer();
        String line;
        while ((line = in.readLine()) != null) {
            sb.append(line);
        }
        in.close();

        return sb.toString();
    } catch (MalformedURLException mue) {
        throw new MetacatUtilException("URL error when contacting: " + urlString + " : " + mue.getMessage());
    } catch (IOException ioe) {
        throw new MetacatUtilException("I/O error when contacting: " + urlString + " : " + ioe.getMessage());
    }
}

From source file:com.android.W3T.app.network.NetworkUtil.java

public static int attemptSendReceipt(String op, Receipt r) {
    // Here we may want to check the network status.
    checkNetwork();/*  w  ww  .  j  ava2s . c  o  m*/
    try {
        JSONObject jsonstr = new JSONObject();

        if (op.equals(METHOD_SEND_RECEIPT)) {
            // Add your data
            JSONObject basicInfo = new JSONObject();
            basicInfo.put("store_account", r.getEntry(ENTRY_STORE_ACC));// store name
            basicInfo.put("currency_mark", r.getEntry(ENTRY_CURRENCY));
            basicInfo.put("store_define_id", r.getEntry(ENTRY_RECEIPT_ID));
            basicInfo.put("source", r.getEntry(ENTRY_SOURCE));
            basicInfo.put("tax", r.getEntry(ENTRY_TAX)); // tax
            basicInfo.put("total_cost", r.getEntry(ENTRY_TOTAL)); // total price
            basicInfo.put("user_account", UserProfile.getUsername());
            JSONObject receipt = new JSONObject();
            receipt.put("receipt", basicInfo);
            receipt.put("items", r.getItemsJsonArray());
            receipt.put("opcode", op);
            receipt.put("acc", UserProfile.getUsername());
            jsonstr.put("json", receipt);
        }
        URL url = new URL(RECEIPT_OP_URL);
        URLConnection connection = url.openConnection();
        connection.setDoOutput(true);

        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
        // Must put "json=" here for server to decoding the data
        String data = "json=" + jsonstr.toString();
        out.write(data);
        out.flush();
        out.close();

        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
        String s = in.readLine();
        System.out.println(s);
        if (Integer.valueOf(s) > 0) {
            return Integer.valueOf(s);
        } else
            return 0;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return 0;
}

From source file:com.buglabs.dragonfly.util.WSHelper.java

/**
 * Post contents of input stream to URL.
 * //from   w ww .  j av a 2s  . co  m
 * @param url
 * @param stream
 * @return
 * @throws IOException
 */
protected static String postBase64(URL url, InputStream stream) throws IOException {
    URLConnection conn = url.openConnection();
    conn.setDoOutput(true);

    byte[] buff = streamToByteArray(stream);

    String em = Base64.encodeBytes(buff);
    OutputStreamWriter osr = new OutputStreamWriter(conn.getOutputStream());
    osr.write(em);
    osr.flush();

    stream.close();
    conn.getOutputStream().flush();
    conn.getOutputStream().close();

    BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line, resp = new String("");
    while ((line = rd.readLine()) != null) {
        resp = resp + line + "\n";
    }
    rd.close();

    return resp;
}

From source file:com.android.W3T.app.network.NetworkUtil.java

public static String attemptGetReceipt(String op, String id) {
    // Here we may want to check the network status.
    checkNetwork();//ww w. j a v  a  2 s .  c om

    try {
        JSONObject jsonstr = new JSONObject();
        JSONObject param = new JSONObject();
        try {
            param.put("opcode", op);
            param.put("acc", UserProfile.getUsername());
            if (op.equals(METHOD_RECEIVE_ALL)) {
                // Add your data
                param.put("limitStart", "0");
                param.put("limitOffset", "7");
            } else if (op.equals(METHOD_RECEIVE_RECEIPT_DETAIL)) {
                // Add your data
                JSONArray rid = new JSONArray();
                rid.put(Integer.valueOf(id));
                param.put("receiptIds", rid);

            } else if (op.equals(METHOD_RECEIVE_RECEIPT_ITEMS)) {
                // Add your data
                JSONArray rid = new JSONArray();
                rid.put(Integer.valueOf(id));
                param.put("receiptIds", rid);
            }
            jsonstr.put("json", param);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        URL url = new URL(RECEIPT_OP_URL);
        URLConnection connection = url.openConnection();
        connection.setDoOutput(true);
        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
        // Must put "json=" here for server to decoding the data
        String data = "json=" + jsonstr.toString();
        out.write(data);
        out.flush();
        out.close();

        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
        String s = in.readLine();

        System.out.println("get " + s);

        return s;

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.android.W3T.app.network.NetworkUtil.java

public static String attemptSearch(String op, int range, String[] terms) {
    // Here we may want to check the network status.
    checkNetwork();/*from w ww. ja  v  a  2  s . co  m*/

    try {
        JSONObject param = new JSONObject();
        param.put("acc", UserProfile.getUsername());
        param.put("opcode", "search");
        param.put("mobile", true);
        JSONObject jsonstr = new JSONObject();
        if (op == METHOD_KEY_SEARCH) {
            // Add your data
            // Add keys if there is any.
            if (terms != null) {
                JSONArray keys = new JSONArray();
                int numTerm = terms.length;
                for (int i = 0; i < numTerm; i++) {
                    keys.put(terms[i]);
                }
                param.put("keys", keys);
            }
            // Calculate the Search Range by last N days
            Calendar c = Calendar.getInstance();
            if (range == -SEVEN_DAYS || range == -FOURTEEN_DAYS) {
                // 7 days or 14 days
                c.add(Calendar.DAY_OF_MONTH, range);
            } else if (range == -ONE_MONTH || range == -THREE_MONTHS) {
                // 1 month or 6 month
                c.add(Calendar.MONTH, range);
            }

            String timeStart = String.valueOf(c.get(Calendar.YEAR));
            timeStart += ("-" + String.valueOf(c.get(Calendar.MONTH) + 1));
            timeStart += ("-" + String.valueOf(c.get(Calendar.DAY_OF_MONTH)));
            Calendar current = Calendar.getInstance();
            current.add(Calendar.DAY_OF_MONTH, 1);
            String timeEnd = String.valueOf(current.get(Calendar.YEAR));
            timeEnd += ("-" + String.valueOf(current.get(Calendar.MONTH) + 1));
            timeEnd += ("-" + String.valueOf(current.get(Calendar.DAY_OF_MONTH)));

            JSONObject timeRange = new JSONObject();
            timeRange.put("start", timeStart);
            timeRange.put("end", timeEnd);
            param.put("timeRange", timeRange);

            jsonstr.put("json", param);
        } else if (op == METHOD_TAG_SEARCH) {

        } else if (op == METHOD_KEY_DATE_SEARCH) {
            if (terms.length > 2) {
                // Add keys if there is any.
                JSONArray keys = new JSONArray();
                int numTerm = terms.length - 2;
                for (int i = 0; i < numTerm; i++) {
                    keys.put(terms[i]);
                }
                param.put("keys", keys);
            } else if (terms.length < 2) {
                System.out.println("Wrong terms: no start or end date.");
                return null;
            }
            JSONObject timeRange = new JSONObject();
            timeRange.put("start", terms[terms.length - 2]);
            timeRange.put("end", terms[terms.length - 1]);
            param.put("timeRange", timeRange);
            jsonstr.put("json", param);
        }
        URL url = new URL(RECEIPT_OP_URL);
        URLConnection connection = url.openConnection();
        connection.setDoOutput(true);

        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
        // Must put "json=" here for server to decoding the data
        String data = "json=" + jsonstr.toString();
        out.write(data);
        out.flush();
        out.close();

        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
        return in.readLine();
        //           String s = in.readLine();
        //           System.out.println(s);
        //           return s;
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

From source file:Downloader.java

/**
 * Creates an URL connection for the specified URL and data.
 * //from  www  .j  a va2  s.  co m
 * @param url The URL to connect to
 * @param postData The POST data to pass to the URL
 * @return An URLConnection for the specified URL/data
 * @throws java.net.MalformedURLException If the specified URL is malformed
 * @throws java.io.IOException If an I/O exception occurs while connecting
 */
private static URLConnection getConnection(final String url, final String postData)
        throws MalformedURLException, IOException {
    final URL myUrl = new URL(url);
    final URLConnection urlConn = myUrl.openConnection();

    urlConn.setUseCaches(false);
    urlConn.setDoInput(true);
    urlConn.setDoOutput(postData.length() > 0);
    urlConn.setConnectTimeout(10000);

    if (postData.length() > 0) {
        urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

        final DataOutputStream out = new DataOutputStream(urlConn.getOutputStream());
        out.writeBytes(postData);
        out.flush();
        out.close();
    }

    return urlConn;
}

From source file:org.wso2.carbon.connector.integration.test.common.ConnectorIntegrationUtil.java

public static int sendRequestToRetriveHeaders(String addUrl, String query, String contentType)
        throws IOException, JSONException {

    String charset = "UTF-8";
    URLConnection connection = new URL(addUrl).openConnection();
    connection.setDoOutput(true);/*from   w w w. ja  va  2  s  .c om*/
    connection.setRequestProperty("Accept-Charset", charset);
    connection.setRequestProperty("Content-Type", contentType + ";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");
            }
        }
    }

    HttpURLConnection httpConn = (HttpURLConnection) connection;
    int responseCode = httpConn.getResponseCode();

    return responseCode;
}

From source file:dictinsight.utils.io.HttpUtils.java

public static String getDataFromOtherServer(String url, String param) {
    PrintWriter out = null;//from  ww  w .  j  ava  2  s . co  m
    BufferedReader in = null;
    String result = "";
    try {
        URL realUrl = new URL(url);
        URLConnection conn = realUrl.openConnection();
        conn.setConnectTimeout(1000 * 10);
        conn.setRequestProperty("accept", "*/*");
        conn.setRequestProperty("connection", "Keep-Alive");
        conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        out = new PrintWriter(conn.getOutputStream());
        out.print(param);
        out.flush();
        in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        while ((line = in.readLine()) != null) {
            result += line;
        }
    } catch (Exception e) {
        System.out.println("get date from " + url + param + " error!");
        e.printStackTrace();
    }
    // finally?????
    finally {
        try {
            if (out != null) {
                out.close();
            }
            if (in != null) {
                in.close();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    return result;
}

From source file:org.wso2.carbon.connector.integration.test.common.ConnectorIntegrationUtil.java

public static JSONObject sendRequest(String addUrl, String query) throws IOException, JSONException {

    String charset = "UTF-8";
    URLConnection connection = new URL(addUrl).openConnection();
    connection.setDoOutput(true);/*from  ww w .  j av  a  2  s  .c  o  m*/
    connection.setRequestProperty("Accept-Charset", charset);
    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");
            }
        }
    }

    HttpURLConnection httpConn = (HttpURLConnection) connection;
    InputStream response;

    if (httpConn.getResponseCode() >= 400) {
        response = httpConn.getErrorStream();
    } else {
        response = connection.getInputStream();
    }

    String out = "{}";
    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));
        }

        if (!sb.toString().trim().isEmpty()) {
            out = sb.toString();
        }
    }

    JSONObject jsonObject = new JSONObject(out);

    return jsonObject;
}

From source file:com.pa165.ddtroops.console.client.Application.java

/**
 * Create new hero in database/*from  w w w  . j a  v  a  2s .  c  o  m*/
 * @param name  hero name
 * @param race  hero race
 * @param xp    hero experience
 */
private static void createHero(String name, String race, String xp) {
    try {
        HeroDTO h = new HeroDTO();
        h.setName(name);
        h.setRace(race);
        h.setXp(Integer.parseInt(xp));
        JSONObject jsonObject = new JSONObject(h);

        URL url = new URL("http://localhost:8080/pa165/rest-jersey-server/hero/post");
        URLConnection connection = url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);
        OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
        out.write(jsonObject.toString());
        out.close();

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

        while (in.readLine() != null) {
        }
        System.out.println("New hero " + h.getName() + " was created.");
        System.out.println();
        in.close();
    } catch (Exception e) {
        System.out.println("\nError when creating new hero");
        System.out.println(e);
    }
}