Example usage for java.net URLConnection setDoOutput

List of usage examples for java.net URLConnection setDoOutput

Introduction

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

Prototype

public void setDoOutput(boolean dooutput) 

Source Link

Document

Sets the value of the doOutput field for this URLConnection to the specified value.

Usage

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();//from  www.  ja v  a 2s. co  m

    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:io.bitsquare.common.util.Utilities.java

public static String readTextFileFromServer(String url, String userAgent) throws IOException {
    URLConnection connection = URI.create(url).toURL().openConnection();
    connection.setDoOutput(true);
    connection.setUseCaches(false);//from   w  w w. j a  v  a  2s . c  om
    connection.setConnectTimeout((int) TimeUnit.SECONDS.toMillis(10));
    connection.addRequestProperty("User-Agent", userAgent);
    connection.connect();
    try (InputStream inputStream = connection.getInputStream()) {
        return CharStreams.toString(new InputStreamReader(inputStream, Charsets.UTF_8));
    } catch (IOException e) {
        e.printStackTrace();
        throw e;
    }
}

From source file:oneDrive.OneDriveAPI.java

public static void uploadFile(String filePath) {
    URLConnection urlconnection = null;
    try {/*from w ww.ja  v a2s.  c om*/
        File file = new File(UPLOAD_PATH + filePath);
        URL url = new URL(DRIVE_PATH + file.getName() + ":/content");
        urlconnection = url.openConnection();
        urlconnection.setDoOutput(true);
        urlconnection.setDoInput(true);

        if (urlconnection instanceof HttpURLConnection) {
            try {
                ((HttpURLConnection) urlconnection).setRequestMethod("PUT");
                ((HttpURLConnection) urlconnection).setRequestProperty("Content-type",
                        "application/octet-stream");
                ((HttpURLConnection) urlconnection).addRequestProperty("Authorization",
                        "Bearer " + ACCESS_TOKEN);
                ((HttpURLConnection) urlconnection).connect();

            } catch (ProtocolException e) {
                e.printStackTrace();
            }
        }

        BufferedOutputStream bos = new BufferedOutputStream(urlconnection.getOutputStream());
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
        int i;
        // read byte by byte until end of stream
        while ((i = bis.read()) >= 0) {
            bos.write(i);
        }
        bos.flush();
        bos.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:BihuHttpUtil.java

public static String doHttpPost(String xmlInfo, String URL) {
    System.out.println("??:" + xmlInfo);
    byte[] xmlData = xmlInfo.getBytes();
    InputStream instr = null;//from w w  w  .j  av  a 2  s.c  o m
    java.io.ByteArrayOutputStream out = null;
    try {
        URL url = new URL(URL);
        URLConnection urlCon = url.openConnection();
        urlCon.setDoOutput(true);
        urlCon.setDoInput(true);
        urlCon.setUseCaches(false);
        urlCon.setRequestProperty("Content-Type", "text/xml");
        urlCon.setRequestProperty("Content-length", String.valueOf(xmlData.length));
        System.out.println(String.valueOf(xmlData.length));
        DataOutputStream printout = new DataOutputStream(urlCon.getOutputStream());
        printout.write(xmlData);
        printout.flush();
        printout.close();
        instr = urlCon.getInputStream();
        byte[] bis = IOUtils.toByteArray(instr);
        String ResponseString = new String(bis, "UTF-8");
        if ((ResponseString == null) || ("".equals(ResponseString.trim()))) {
            System.out.println("");
        }
        System.out.println("?:" + ResponseString);
        return ResponseString;

    } catch (Exception e) {
        e.printStackTrace();
        return "0";
    } finally {
        try {
            out.close();
            instr.close();
        } catch (Exception ex) {
            return "0";
        }
    }
}

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();// w w  w. j a v a 2  s . c om

    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:org.royaldev.royalcommands.VUUpdater.java

/**
 * Gets the update information from the title of the latest file available from the CurseForge API.
 *
 * @param pluginID ID of the plugin to get the information from. The ID comes from CurseForge.
 * @return {@link org.royaldev.royalcommands.VUUpdater.VUUpdateInfo}
 * @throws IOException If any errors occur
 *//*from  www .  j a v  a 2s  . c om*/
public static VUUpdateInfo getUpdateInfo(String pluginID) throws IOException {
    final URLConnection conn = new URL("https://api.curseforge.com/servermods/files?projectIds=" + pluginID)
            .openConnection();
    conn.setConnectTimeout(5000);
    conn.setRequestProperty("User-Agent", "VU/1.0");
    conn.setDoOutput(true);
    final BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    final String response = reader.readLine();
    final JSONArray array = (JSONArray) JSONValue.parse(response);
    final Matcher m = VUUpdater.vuPattern
            .matcher((String) ((JSONObject) array.get(array.size() - 1)).get("name"));
    if (!m.matches())
        throw new IllegalArgumentException("No match found!");
    final byte[] vuBytes = VUUpdater.hexStringToByteArray(m.group(4));
    return new VUUpdateInfo(m.group(2), vuBytes);
}

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

/**
 * Utility method to create a URL connection
 * /*from   w  w w.j  a  v a  2s .c  o m*/
 * @param urlValue
 * @param doPost
 *            is this for a HTTP POST
 * @return
 * @throws Exception
 */
private static URLConnection getUrlConnection(String urlValue, boolean doPost) throws Exception {
    URL url = new URL(urlValue);
    URLConnection urlConnection = url.openConnection();
    urlConnection.setConnectTimeout(0);
    urlConnection.setReadTimeout(0);
    if (doPost) {
        urlConnection.setDoOutput(true);
    }
    return urlConnection;
}

From source file:net.pms.util.OpenSubtitle.java

public static String postPage(URLConnection connection, String query) throws IOException {
    connection.setDoOutput(true);
    connection.setDoInput(true);//from  w w  w .java  2 s. c o m
    connection.setUseCaches(false);
    connection.setDefaultUseCaches(false);
    connection.setRequestProperty("Content-Type", "text/xml");
    connection.setRequestProperty("Content-Length", "" + query.length());
    ((HttpURLConnection) connection).setRequestMethod("POST");
    //LOGGER.debug("opensub query "+query);
    // open up the output stream of the connection
    if (!StringUtils.isEmpty(query)) {
        try (DataOutputStream output = new DataOutputStream(connection.getOutputStream())) {
            output.writeBytes(query);
            output.flush();
        }
    }

    StringBuilder page;
    try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
        page = new StringBuilder();
        String str;
        while ((str = in.readLine()) != null) {
            page.append(str.trim());
            page.append("\n");
        }
    }
    //LOGGER.debug("opensubs result page "+page.toString());
    return page.toString();
}

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

public static String getDataFromOtherServer(String url, String param) {
    PrintWriter out = null;/* ww  w.j  a va 2s.  c o 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:net.pms.util.OpenSubtitle.java

public static String fetchSubs(String url, String outName) throws FileNotFoundException, IOException {
    if (!login()) {
        return "";
    }/*from w w w  .ja va  2s. co  m*/
    if (StringUtils.isEmpty(outName)) {
        outName = subFile(String.valueOf(System.currentTimeMillis()));
    }
    File f = new File(outName);
    URL u = new URL(url);
    URLConnection connection = u.openConnection();
    connection.setDoInput(true);
    connection.setDoOutput(true);
    InputStream in = connection.getInputStream();
    OutputStream out;
    try (GZIPInputStream gzipInputStream = new GZIPInputStream(in)) {
        out = new FileOutputStream(f);
        byte[] buf = new byte[4096];
        int len;
        while ((len = gzipInputStream.read(buf)) > 0) {
            out.write(buf, 0, len);
        }
    }
    out.close();
    if (!PMS.getConfiguration().isLiveSubtitlesKeep()) {
        int tmo = PMS.getConfiguration().getLiveSubtitlesTimeout();
        if (tmo <= 0) {
            PMS.get().addTempFile(f);
        } else {
            PMS.get().addTempFile(f, tmo);
        }
    }
    return f.getAbsolutePath();
}