Example usage for java.net HttpURLConnection setDoInput

List of usage examples for java.net HttpURLConnection setDoInput

Introduction

In this page you can find the example usage for java.net HttpURLConnection setDoInput.

Prototype

public void setDoInput(boolean doinput) 

Source Link

Document

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

Usage

From source file:fi.hip.sicx.store.HIPStoreClient.java

/**
 * Gets a file stored in the cloud and saves to a local disk.
 * /* www.j a va 2  s  . c om*/
 * @param cloudFile The file in the cloud that is to be saved.
 * @param localOutFile The saved file name.
 * @return true if file saved successfully, otherwise false
 */
@Override
public boolean getFile(String cloudFile, String localOutFile, StorageClientObserver sco) {

    boolean ok = false;
    HttpURLConnection conn = null;
    try {
        String data = URLEncoder.encode("path", "UTF-8") + "=" + URLEncoder.encode(cloudFile, "UTF-8");

        conn = getConnection("/store/fetch");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(data);
        wr.flush();

        if (conn.getResponseCode() == 200) {

            InputStream in = conn.getInputStream();

            long total = conn.getContentLength();
            long sent = 0;

            System.out.println("content len is " + total);

            FileOutputStream out = new FileOutputStream(localOutFile);
            byte[] buf = new byte[1024 * 64];
            int r = 0;
            while ((r = in.read(buf)) > -1) {
                out.write(buf, 0, r);
                sent += r;
                sco.progressMade((int) ((sent * 100) / total));
            }
            out.close();
            ok = true;
        }

    } catch (Exception e) {
        e.printStackTrace();
        failed = true;
    }

    closeConnection(conn);
    return ok;
}

From source file:eu.codeplumbers.cosi.services.CosiExpenseService.java

public void sendChangesToCozy() {
    List<Expense> unSyncedExpenses = Expense.getAllUnsynced();
    int i = 0;/* w  w w.  j  a  va  2  s .c om*/
    for (Expense expense : unSyncedExpenses) {
        URL urlO = null;
        try {
            JSONObject jsonObject = expense.toJsonObject();
            mBuilder.setProgress(unSyncedExpenses.size(), i + 1, false);
            mBuilder.setContentText("Syncing " + jsonObject.getString("docType") + ":");
            mNotifyManager.notify(notification_id, mBuilder.build());
            EventBus.getDefault().post(
                    new ExpenseSyncEvent(SYNC_MESSAGE, getString(R.string.lbl_expense_status_read_phone)));
            String remoteId = jsonObject.getString("remoteId");
            String requestMethod = "";

            if (remoteId.isEmpty()) {
                urlO = new URL(syncUrl);
                requestMethod = "POST";
            } else {
                urlO = new URL(syncUrl + remoteId + "/");
                requestMethod = "PUT";
            }

            HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
            conn.setConnectTimeout(5000);
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            conn.setRequestProperty("Authorization", authHeader);
            conn.setDoOutput(true);
            conn.setDoInput(true);

            conn.setRequestMethod(requestMethod);

            // set request body
            jsonObject.remove("remoteId");
            long objectId = jsonObject.getLong("id");
            jsonObject.remove("id");
            OutputStream os = conn.getOutputStream();
            os.write(jsonObject.toString().getBytes("UTF-8"));
            os.flush();

            // read the response
            InputStream in = new BufferedInputStream(conn.getInputStream());

            StringWriter writer = new StringWriter();
            IOUtils.copy(in, writer, "UTF-8");
            String result = writer.toString();

            JSONObject jsonObjectResult = new JSONObject(result);

            if (jsonObjectResult != null && jsonObjectResult.has("_id")) {
                result = jsonObjectResult.getString("_id");
                expense.setRemoteId(result);
                expense.save();
            }

            in.close();
            conn.disconnect();

        } catch (MalformedURLException e) {
            EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            e.printStackTrace();
            stopSelf();
        } catch (ProtocolException e) {
            EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            e.printStackTrace();
            stopSelf();
        } catch (IOException e) {
            EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            e.printStackTrace();
            stopSelf();
        } catch (JSONException e) {
            EventBus.getDefault().post(new ExpenseSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            e.printStackTrace();
            stopSelf();
        }
        i++;
    }
}

From source file:core.AbstractTest.java

private HttpURLConnection getHttpConnection(String sUrl, String sMethod) {
    URL uri = null;//from ww w  . j  a  v  a  2  s . com
    HttpURLConnection conn = null;

    try {
        uri = new URL(sUrl);
        conn = (HttpURLConnection) uri.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setRequestMethod(sMethod); // POST, PUT, DELETE, GET
        conn.setUseCaches(false);
        conn.setRequestProperty("Cache-Control", "no-cache");
        conn.setRequestProperty("Connection", "Keep-Alive");
        //conn.setConnectTimeout(60000); //60 secs
        //conn.setReadTimeout(60000); //60 secs
        //conn.setRequestProperty("Accept-Encoding", "UTF-8");
    } catch (Exception e) {
        Assert.fail("Unable to get HttpConnection " + e.getMessage());
    }

    return conn;
}

From source file:mdretrieval.FileFetcher.java

public static String[] loadStringFromURL(String destinationURL, boolean acceptRDF) throws IOException {
    String[] ret = new String[2];

    HttpURLConnection urlConnection = null;
    InputStream inputStream = null;

    String dest = destinationURL;
    URL url = new URL(dest);
    Proxy proxy = null;//  w ww .  ja  v a  2s .  co m

    if (ServerConstants.isProxyEnabled) {
        proxy = new Proxy(Proxy.Type.HTTP,
                new InetSocketAddress(ServerConstants.hostname, ServerConstants.port));
        urlConnection = (HttpURLConnection) url.openConnection(proxy);
    } else {
        urlConnection = (HttpURLConnection) url.openConnection();
    }

    boolean redirect = false;

    int status = urlConnection.getResponseCode();
    if (Master.DEBUG_LEVEL >= Master.LOW)
        System.out.println("RESPONSE-CODE--> " + status);
    if (status != HttpURLConnection.HTTP_OK) {
        if (status == HttpURLConnection.HTTP_MOVED_TEMP || status == HttpURLConnection.HTTP_MOVED_PERM
                || status == HttpURLConnection.HTTP_SEE_OTHER)
            redirect = true;
    }

    if (redirect) {
        String newUrl = urlConnection.getHeaderField("Location");
        dest = newUrl;
        urlConnection.disconnect();
        if (Master.DEBUG_LEVEL > Master.LOW)
            System.out.println("REDIRECT--> " + newUrl);
        urlConnection = openMaybeProxyConnection(proxy, newUrl);
    }

    try {
        urlConnection.setRequestMethod("GET");
        urlConnection.setRequestProperty("Accept", HTTP_RDFXML_PROP);
        urlConnection.setDoInput(true);
        //urlConnection.setDoOutput(true);            
        inputStream = urlConnection.getInputStream();
        ret[1] = urlConnection.getHeaderField("Content-Type");
    } catch (IllegalStateException e) {
        if (Master.DEBUG_LEVEL >= Master.LOW)
            System.out.println(" DEBUG: IllegalStateException");
        urlConnection.disconnect();
        HttpURLConnection conn2 = openMaybeProxyConnection(proxy, dest);
        conn2.setRequestMethod("GET");
        conn2.setRequestProperty("Accept", HTTP_RDFXML_PROP);
        conn2.setDoInput(true);
        inputStream = conn2.getInputStream();
        ret[1] = conn2.getHeaderField("Content-Type");
    }

    try {
        ret[0] = IOUtils.toString(inputStream);

        if (Master.DEBUG_LEVEL > Master.LOW) {
            System.out.println(" Content-type: " + urlConnection.getHeaderField("Content-Type"));
        }
    } finally {
        IOUtils.closeQuietly(inputStream);
        urlConnection.disconnect();
    }

    if (Master.DEBUG_LEVEL > Master.LOW)
        System.out.println("Done reading " + destinationURL);
    return ret;

}

From source file:eu.codeplumbers.cosi.services.CosiSmsService.java

private List<Sms> getRemoteMessages() {
    allSms.clear();/*from   www  .j a  v  a  2 s.co m*/
    URL urlO = null;
    try {
        urlO = new URL(designUrl);
        HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        conn.setRequestProperty("Authorization", authHeader);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");

        // read the response
        int status = conn.getResponseCode();
        InputStream in = null;

        if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
            in = conn.getErrorStream();
        } else {
            in = conn.getInputStream();
        }

        StringWriter writer = new StringWriter();
        IOUtils.copy(in, writer, "UTF-8");
        String result = writer.toString();

        JSONArray jsonArray = new JSONArray(result);

        if (jsonArray != null) {
            if (jsonArray.length() == 0) {
                EventBus.getDefault()
                        .post(new SmsSyncEvent(SYNC_MESSAGE, "Your Cozy has no Text messages stored."));
                Sms.setAllUnsynced();
            } else {
                for (int i = 0; i < jsonArray.length(); i++) {
                    mBuilder.setProgress(jsonArray.length(), i, false);
                    mNotifyManager.notify(notification_id, mBuilder.build());
                    EventBus.getDefault()
                            .post(new SmsSyncEvent(SYNC_MESSAGE, getString(R.string.lbl_sms_status_read_cozy)));

                    JSONObject smsJson = jsonArray.getJSONObject(i).getJSONObject("value");
                    Sms sms = Sms.getBySystemIdAddressAndBody(smsJson.get("systemId").toString(),
                            smsJson.getString("address"), smsJson.getString("body"));
                    if (sms == null) {
                        sms = new Sms(smsJson);
                    } else {
                        sms.setRemoteId(smsJson.getString("_id"));
                        sms.setSystemId(smsJson.getString("systemId"));
                        sms.setAddress(smsJson.getString("address"));
                        sms.setBody(smsJson.getString("body"));

                        if (smsJson.has("readState")) {
                            sms.setReadState(smsJson.getBoolean("readState"));
                        }

                        sms.setDateAndTime(smsJson.getString("dateAndTime"));
                        sms.setType(smsJson.getInt("type"));
                    }

                    sms.save();

                    allSms.add(sms);
                }
            }
        } else {
            errorMessage = "Failed to parse API response";
            EventBus.getDefault().post(new SmsSyncEvent(SERVICE_ERROR, "Failed to parse API response"));
        }

        in.close();
        conn.disconnect();

    } catch (MalformedURLException e) {
        e.printStackTrace();
        errorMessage = e.getLocalizedMessage();
    } catch (ProtocolException e) {
        errorMessage = e.getLocalizedMessage();
        e.printStackTrace();
    } catch (IOException e) {
        errorMessage = e.getLocalizedMessage();
        e.printStackTrace();
    } catch (JSONException e) {
        errorMessage = e.getLocalizedMessage();
        e.printStackTrace();
    }
    return allSms;
}

From source file:com.cts.ptms.carrier.ups.UPSHTTPClient.java

/**
 * This method establish the connection to the REST service
 *///  ww  w.ja va2s . co  m
private String contactService(String xmlInputString, String serviceUrl) throws Exception {
    String outputStr = null;
    OutputStream outputStream = null;
    try {

        URL url = new URL(serviceUrl);
        //System.getProperties().put("https.proxyHost", "proxy.cognizant.com");
        // System.getProperties().put("https.proxyPort", "6050"); 
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        //   connection.setRequestProperty("User-Agent", "Mozilla/4.5");
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setUseCaches(false);
        xmlInputString = xmlInputString.replace(ShippingConstants.XML_STANDALONE_STRING, "");
        outputStream = connection.getOutputStream();
        outputStream.write(xmlInputString.getBytes());
        outputStream.flush();
        outputStream.close();
        outputStr = readURLConnection(connection);
    } catch (Exception e) {
        throw e;
    } finally {
        if (outputStream != null) {
            outputStream.close();
            outputStream = null;
        }
    }
    return outputStr;
}

From source file:com.nubits.nubot.notifications.jhipchat.HipChat.java

public User getUser(UserId id) {
    String query = String.format(HipChatConstants.USERS_SHOW_QUERY_FORMAT, id.getId(),
            HipChatConstants.JSON_FORMAT, authToken);

    InputStream input = null;/*from  w  ww  .  j  a  va 2  s .  c  om*/
    User result = null;
    HttpURLConnection connection = null;

    try {
        URL requestUrl = new URL(HipChatConstants.API_BASE + HipChatConstants.USERS_SHOW + query);
        connection = (HttpURLConnection) requestUrl.openConnection();
        connection.setDoInput(true);
        input = connection.getInputStream();
        result = UserParser.parseUser(this, input);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(input);
        connection.disconnect();
    }

    return result;
}

From source file:com.nubits.nubot.notifications.jhipchat.HipChat.java

public List<Room> listRooms() {
    String query = String.format(HipChatConstants.ROOMS_LIST_QUERY_FORMAT, HipChatConstants.JSON_FORMAT,
            authToken);/*from w ww  .  ja v a 2  s.com*/

    InputStream input = null;
    List<Room> results = null;
    HttpURLConnection connection = null;

    try {
        URL requestUrl = new URL(HipChatConstants.API_BASE + HipChatConstants.ROOMS_LIST + query);
        connection = (HttpURLConnection) requestUrl.openConnection();
        connection.setDoInput(true);
        input = connection.getInputStream();
        results = RoomParser.parseRoomList(this, input);

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(input);
        connection.disconnect();
    }

    return results;
}

From source file:com.nubits.nubot.notifications.jhipchat.HipChat.java

public Room getRoom(String roomId) {
    String query = String.format(HipChatConstants.ROOMS_SHOW_QUERY_FORMAT, roomId, HipChatConstants.JSON_FORMAT,
            authToken);//w  w w.  j a  v a  2  s  .  co  m

    InputStream input = null;
    Room result = null;
    HttpURLConnection connection = null;

    try {
        URL requestUrl = new URL(HipChatConstants.API_BASE + HipChatConstants.ROOMS_SHOW + query);
        connection = (HttpURLConnection) requestUrl.openConnection();
        connection.setDoInput(true);
        input = connection.getInputStream();
        result = RoomParser.parseRoom(this, input);

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(input);
        connection.disconnect();
    }

    return result;
}

From source file:com.nubits.nubot.notifications.jhipchat.HipChat.java

public List<User> listUsers() {
    String query = String.format(HipChatConstants.USERS_LIST_QUERY_FORMAT, HipChatConstants.JSON_FORMAT,
            authToken);/*from ww w . j a  va2 s .  co  m*/

    InputStream input = null;
    List<User> results = null;
    HttpURLConnection connection = null;

    try {
        URL requestUrl = new URL(HipChatConstants.API_BASE + HipChatConstants.USERS_LIST + query);
        connection = (HttpURLConnection) requestUrl.openConnection();
        connection.setDoInput(true);
        input = connection.getInputStream();
        results = UserParser.parseUserList(this, input);

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        IOUtils.closeQuietly(input);
        connection.disconnect();
    }

    return results;
}