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:org.runnerup.export.GoogleFitSynchronizer.java

private HttpURLConnection getHttpURLConnection(String suffix, RequestMethod requestMethod) throws IOException {
    URL url = new URL(REST_URL + suffix);
    HttpURLConnection connect = (HttpURLConnection) url.openConnection();
    connect.addRequestProperty("Authorization", "Bearer " + getAccessToken());
    connect.addRequestProperty("Accept-Encoding", "gzip");
    connect.addRequestProperty("User-Agent", "RunnerUp (gzip)");
    if (requestMethod.equals(RequestMethod.GET)) {
        connect.setDoInput(true);/*from  w  w w.j  a  v a 2  s .co  m*/
    } else {
        connect.setDoOutput(true);
        connect.addRequestProperty("Content-Type", "application/json; charset=UTF-8");
        connect.addRequestProperty("Content-Encoding", "gzip");
    }
    if (requestMethod.equals(RequestMethod.PATCH)) {
        connect.addRequestProperty("X-HTTP-Method-Override", "PATCH");
        connect.setRequestMethod(RequestMethod.POST.name());
    } else {
        connect.setRequestMethod(requestMethod.name());
    }
    return connect;
}

From source file:com.galileha.smarthome.SmartHome.java

/**
 * Read home.json from Server//  w ww .j  a  v  a 2s .c  o m
 * 
 * @param URL
 * @return
 * @throws IOException
 *             , MalformedURLException, JSONException
 */
public void getHomeStatus() throws IOException, MalformedURLException, JSONException {
    // Set URL
    // Connect to Intel Galileo get Device Status
    HttpURLConnection httpCon = (HttpURLConnection) homeJSONUrl.openConnection();
    httpCon.setReadTimeout(10000);
    httpCon.setConnectTimeout(15000);
    httpCon.setRequestMethod("GET");
    httpCon.setDoInput(true);
    httpCon.connect();
    // Read JSON File as InputStream
    InputStream readStream = httpCon.getInputStream();
    Scanner scan = new Scanner(readStream).useDelimiter("\\A");
    // Set stream to String
    String jsonFile = scan.hasNext() ? scan.next() : "";
    // Initialize serveFile as read string
    homeInfo = new JSONObject(jsonFile);
    httpCon.disconnect();
}

From source file:eu.codeplumbers.cosi.api.tasks.SyncDocumentTask.java

@Override
protected String doInBackground(JSONObject... jsonObjects) {
    for (int i = 0; i < jsonObjects.length; i++) {
        JSONObject jsonObject = jsonObjects[i];

        URL urlO = null;/*www  .  jav a2s.c  om*/
        try {
            publishProgress("Syncing " + jsonObject.getString("docType") + ":", i + "",
                    jsonObjects.length + "");
            String remoteId = jsonObject.getString("remoteId");
            String requestMethod = "";

            if (remoteId.isEmpty()) {
                urlO = new URL(url);
                requestMethod = "POST";
            } else {
                urlO = new URL(url + 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");
            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");

                if (jsonObject.get("docType").equals("Sms")) {
                    Sms sms = Sms.load(Sms.class, objectId);
                    sms.setRemoteId(result);
                    sms.save();
                }

                if (jsonObject.get("docType").equals("Note")) {
                    Note note = Note.load(Note.class, objectId);
                    note.setRemoteId(result);
                    note.save();
                }

                if (jsonObject.get("docType").equals("Call")) {
                    Call call = Call.load(Call.class, objectId);
                    call.setRemoteId(result);
                    call.save();
                }

                if (jsonObject.get("docType").equals("Expense")) {
                    Expense expense = Expense.load(Expense.class, objectId);
                    expense.setRemoteId(result);
                    expense.save();
                }
            }

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

        } catch (MalformedURLException e) {
            result = "error";
            e.printStackTrace();
            errorMessage = e.getLocalizedMessage();
        } catch (ProtocolException e) {
            result = "error";
            errorMessage = e.getLocalizedMessage();
            e.printStackTrace();
        } catch (IOException e) {
            result = "error";
            errorMessage = e.getLocalizedMessage();
            e.printStackTrace();
        } catch (JSONException e) {
            result = "error";
            errorMessage = e.getLocalizedMessage();
            e.printStackTrace();
        }
    }

    return result;
}

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

@Override
protected void onHandleIntent(Intent intent) {
    // Do the task here
    Log.i(CosiNoteService.class.getName(), "Cosi Service running");

    // Release the wake lock provided by the WakefulBroadcastReceiver.
    WakefulBroadcastReceiver.completeWakefulIntent(intent);

    Device device = Device.registeredDevice();

    // delete all local notes
    new Delete().from(Note.class).execute();

    // cozy register device url
    this.url = device.getUrl() + "/ds-api/request/note/cosiall/";

    // concatenate username and password with colon for authentication
    final String credentials = device.getLogin() + ":" + device.getPassword();
    authHeader = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);

    showNotification();//from  w  w  w  . ja va2 s  .com

    if (isNetworkAvailable()) {
        try {
            URL urlO = new URL(url);
            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) {
                for (int i = 0; i < jsonArray.length(); i++) {
                    String version = "0";
                    if (jsonArray.getJSONObject(i).has("version")) {
                        version = jsonArray.getJSONObject(i).getString("version");
                    }
                    JSONObject noteJson = jsonArray.getJSONObject(i).getJSONObject("value");
                    Note note = Note.getByRemoteId(noteJson.get("_id").toString());

                    if (note == null) {
                        note = new Note(noteJson);
                    } else {
                        boolean versionIncremented = note.getVersion() < Integer
                                .valueOf(noteJson.getString("version"));

                        int modifiedOnServer = DateUtils.compareDateStrings(
                                Long.valueOf(note.getLastModificationValueOf()),
                                noteJson.getLong("lastModificationValueOf"));

                        if (versionIncremented || modifiedOnServer == -1) {
                            note.setTitle(noteJson.getString("title"));
                            note.setContent(noteJson.getString("content"));
                            note.setCreationDate(noteJson.getString("creationDate"));
                            note.setLastModificationDate(noteJson.getString("lastModificationDate"));
                            note.setLastModificationValueOf(noteJson.getString("lastModificationValueOf"));
                            note.setParentId(noteJson.getString("parent_id"));
                            // TODO: 10/3/16
                            // handle note paths
                            note.setPath(noteJson.getString("path"));
                            note.setVersion(Integer.valueOf(version));
                        }

                    }

                    mBuilder.setProgress(jsonArray.length(), i, false);
                    mBuilder.setContentText("Getting note : " + note.getTitle());
                    mNotifyManager.notify(notification_id, mBuilder.build());

                    EventBus.getDefault()
                            .post(new NoteSyncEvent(SYNC_MESSAGE, "Getting note : " + note.getTitle()));
                    note.save();
                }
            } else {
                EventBus.getDefault().post(new NoteSyncEvent(SERVICE_ERROR, "Failed to parse API response"));
            }

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

            mNotifyManager.cancel(notification_id);
            EventBus.getDefault().post(new NoteSyncEvent(REFRESH, "Sync OK"));
        } catch (MalformedURLException e) {
            EventBus.getDefault().post(new NoteSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            mNotifyManager.notify(notification_id, mBuilder.build());
            stopSelf();
        } catch (ProtocolException e) {
            EventBus.getDefault().post(new NoteSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            mNotifyManager.notify(notification_id, mBuilder.build());
            stopSelf();
        } catch (IOException e) {
            EventBus.getDefault().post(new NoteSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            mNotifyManager.notify(notification_id, mBuilder.build());
            stopSelf();
        } catch (JSONException e) {
            EventBus.getDefault().post(new NoteSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            mNotifyManager.notify(notification_id, mBuilder.build());
            stopSelf();
        }
    } else {
        mSyncRunning = false;
        EventBus.getDefault().post(new NoteSyncEvent(SERVICE_ERROR, "No Internet connection"));
        mBuilder.setContentText("Sync failed because no Internet connection was available");
        mNotifyManager.notify(notification_id, mBuilder.build());
    }
}

From source file:net.sbbi.upnp.messages.ActionMessage.java

/**
 * Executes the message and retuns the UPNP device response, according to the UPNP specs,
 * this method could take up to 30 secs to process ( time allowed for a device to respond to a request )
 * @return a response object containing the UPNP parsed response
 * @throws IOException if some IOException occurs during message send and reception process
 * @throws UPNPResponseException if an UPNP error message is returned from the server
 *         or if some parsing exception occurs ( detailErrorCode = 899, detailErrorDescription = SAXException message )
 */// ww  w.  ja  va  2  s  .  co  m
public ActionResponse service() throws IOException, UPNPResponseException {
    ActionResponse rtrVal = null;
    UPNPResponseException upnpEx = null;
    IOException ioEx = null;
    StringBuffer body = new StringBuffer(256);

    body.append("<?xml version=\"1.0\"?>\r\n");
    body.append("<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"");
    body.append(" s:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">");
    body.append("<s:Body>");
    body.append("<u:").append(serviceAction.getName()).append(" xmlns:u=\"").append(service.getServiceType())
            .append("\">");

    if (serviceAction.getInputActionArguments() != null) {
        // this action requires params so we just set them...
        for (Iterator itr = inputParameters.iterator(); itr.hasNext();) {
            InputParamContainer container = (InputParamContainer) itr.next();
            body.append("<").append(container.name).append(">").append(container.value);
            body.append("</").append(container.name).append(">");
        }
    }
    body.append("</u:").append(serviceAction.getName()).append(">");
    body.append("</s:Body>");
    body.append("</s:Envelope>");

    if (log.isDebugEnabled())
        log.debug("POST prepared for URL " + service.getControlURL());
    URL url = new URL(service.getControlURL().toString());
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setUseCaches(false);
    conn.setRequestMethod("POST");
    HttpURLConnection.setFollowRedirects(false);
    //conn.setConnectTimeout( 30000 );
    conn.setRequestProperty("HOST", url.getHost() + ":" + url.getPort());
    conn.setRequestProperty("CONTENT-TYPE", "text/xml; charset=\"utf-8\"");
    conn.setRequestProperty("CONTENT-LENGTH", Integer.toString(body.length()));
    conn.setRequestProperty("SOAPACTION",
            "\"" + service.getServiceType() + "#" + serviceAction.getName() + "\"");
    OutputStream out = conn.getOutputStream();
    out.write(body.toString().getBytes());
    out.flush();
    out.close();
    conn.connect();
    InputStream input = null;

    if (log.isDebugEnabled())
        log.debug("executing query :\n" + body);
    try {
        input = conn.getInputStream();
    } catch (IOException ex) {
        // java can throw an exception if he error code is 500 or 404 or something else than 200
        // but the device sends 500 error message with content that is required
        // this content is accessible with the getErrorStream
        input = conn.getErrorStream();
    }

    if (input != null) {
        int response = conn.getResponseCode();
        String responseBody = getResponseBody(input);
        if (log.isDebugEnabled())
            log.debug("received response :\n" + responseBody);
        SAXParserFactory saxParFact = SAXParserFactory.newInstance();
        saxParFact.setValidating(false);
        saxParFact.setNamespaceAware(true);
        ActionMessageResponseParser msgParser = new ActionMessageResponseParser(serviceAction);
        StringReader stringReader = new StringReader(responseBody);
        InputSource src = new InputSource(stringReader);
        try {
            SAXParser parser = saxParFact.newSAXParser();
            parser.parse(src, msgParser);
        } catch (ParserConfigurationException confEx) {
            // should never happen
            // we throw a runtimeException to notify the env problem
            throw new RuntimeException(
                    "ParserConfigurationException during SAX parser creation, please check your env settings:"
                            + confEx.getMessage());
        } catch (SAXException saxEx) {
            // kind of tricky but better than nothing..
            upnpEx = new UPNPResponseException(899, saxEx.getMessage());
        } finally {
            try {
                input.close();
            } catch (IOException ex) {
                // ignore
            }
        }
        if (upnpEx == null) {
            if (response == HttpURLConnection.HTTP_OK) {
                rtrVal = msgParser.getActionResponse();
            } else if (response == HttpURLConnection.HTTP_INTERNAL_ERROR) {
                upnpEx = msgParser.getUPNPResponseException();
            } else {
                ioEx = new IOException("Unexpected server HTTP response:" + response);
            }
        }
    }
    try {
        out.close();
    } catch (IOException ex) {
        // ignore
    }
    conn.disconnect();
    if (upnpEx != null) {
        throw upnpEx;
    }
    if (rtrVal == null && ioEx == null) {
        ioEx = new IOException("Unable to receive a response from the UPNP device");
    }
    if (ioEx != null) {
        throw ioEx;
    }
    return rtrVal;
}

From source file:com.adaptris.core.http.JdkHttpProducer.java

@Override
protected AdaptrisMessage doRequest(AdaptrisMessage msg, ProduceDestination destination, long timeout)
        throws ProduceException {

    AdaptrisMessage reply = defaultIfNull(getMessageFactory()).newMessage();
    ThreadLocalCredentials threadLocalCreds = null;
    try {/*from ww  w.ja  v a  2s  .c om*/
        URL url = new URL(destination.getDestination(msg));
        if (getPasswordAuthentication() != null) {
            Authenticator.setDefault(AdapterResourceAuthenticator.getInstance());
            threadLocalCreds = ThreadLocalCredentials.getInstance(url.toString());
            threadLocalCreds.setThreadCredentials(getPasswordAuthentication());
            AdapterResourceAuthenticator.getInstance().addAuthenticator(threadLocalCreds);
        }
        HttpURLConnection http = (HttpURLConnection) url.openConnection();
        http.setRequestMethod(methodToUse(msg).name());
        http.setInstanceFollowRedirects(handleRedirection());
        http.setDoInput(true);
        http.setConnectTimeout(Long.valueOf(timeout).intValue());
        http.setReadTimeout(Long.valueOf(timeout).intValue());
        // ProxyUtil.applyBasicProxyAuthorisation(http);
        addHeaders(msg, http);
        if (getContentTypeKey() != null && msg.containsKey(getContentTypeKey())) {
            http.setRequestProperty(CONTENT_TYPE, msg.getMetadataValue(getContentTypeKey()));
        }
        // if (getAuthorisation() != null) {
        // http.setRequestProperty(AUTHORIZATION, getAuthorisation());
        // }
        // logHeaders("Request Information", "Request Method : " + http.getRequestMethod(), http.getRequestProperties().entrySet());
        sendMessage(msg, http);
        readResponse(http, reply);
        // logHeaders("Response Information", http.getResponseMessage(), http.getHeaderFields().entrySet());
    } catch (IOException e) {
        throw new ProduceException(e);
    } catch (CoreException e) {
        if (e instanceof ProduceException) {
            throw (ProduceException) e;
        } else {
            throw new ProduceException(e);
        }
    } finally {
        if (threadLocalCreds != null) {
            threadLocalCreds.removeThreadCredentials();
            AdapterResourceAuthenticator.getInstance().removeAuthenticator(threadLocalCreds);
        }
    }
    return reply;
}

From source file:com.galileha.smarthome.SmartHome.java

/**
 * Get Command List JSON File From Server
 * /* w w w. ja  v a  2s .com*/
 * @throws IOException
 * @throws MalformedURLException
 * @throws JSONException
 */
public void getCommandsList() throws IOException, MalformedURLException, JSONException {
    // Connect to Intel Galileo get Commands List
    HttpURLConnection httpCon = (HttpURLConnection) commandsJSONUrl.openConnection();
    httpCon.setReadTimeout(10000);
    httpCon.setConnectTimeout(15000);
    httpCon.setRequestMethod("GET");
    httpCon.setDoInput(true);
    httpCon.connect();
    // Read JSON File as InputStream
    InputStream readCommand = httpCon.getInputStream();
    Scanner scanCommand = new Scanner(readCommand).useDelimiter("\\A");
    // Set stream to String
    String commandFile = scanCommand.hasNext() ? scanCommand.next() : "";
    // Initialize serveFile as read string
    JSONObject commandsList = new JSONObject(commandFile);
    JSONObject temp = (JSONObject) commandsList.get("commands");
    JSONArray comArray = (JSONArray) temp.getJSONArray("command");
    int numberOfCommands = comArray.length();
    commands = new String[numberOfCommands];
    // Fill the Array
    for (int i = 0; i < numberOfCommands; i++) {
        JSONObject commandObject = (JSONObject) comArray.get(i);
        commands[i] = commandObject.getString("text");
    }
    Log.d("JSON", "Loaded " + commands[2]);
    httpCon.disconnect();
}

From source file:com.android.volley.toolbox.http.HurlStack.java

/**
 * Opens an {@link HttpURLConnection} with parameters.
 *
 * @param url//from   www .j  ava2 s.  co  m
 * @return an open connection
 * @throws IOException
 */
private HttpURLConnection openConnection(URL url, Request<?> request) throws IOException {
    HttpURLConnection connection = createConnection(url);

    int timeoutMs = request.getTimeoutMs();
    connection.setConnectTimeout(timeoutMs);
    connection.setReadTimeout(timeoutMs);
    connection.setUseCaches(false);
    connection.setDoInput(true);
    // use caller-provided custom SslSocketFactory, if any, for HTTPS
    if ("https".equals(url.getProtocol()) && mSslSocketFactory != null) {
        ((HttpsURLConnection) connection).setSSLSocketFactory(mSslSocketFactory);
    }
    return connection;
}

From source file:yulei.android.client.AndroidMobilePushApp.java

private String downloadUrl(String myurl) throws IOException {
    InputStream is = null;/*from w w w  .j  a v  a  2 s  .  co m*/
    // Only display the first 500 characters of the retrieved
    // web page content.
    int len = 500;

    try {
        URL url = new URL(myurl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(50000 /* milliseconds */);
        conn.setConnectTimeout(85000 /* milliseconds */);
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        // Starts the query
        conn.connect();
        int response = conn.getResponseCode();
        Log.d(DEBUG_TAG, "The response is: " + response);
        is = conn.getInputStream();

        // Convert the InputStream into a string
        String contentAsString = readIt(is, len);
        return contentAsString;

        // Makes sure that the InputStream is closed after the app is
        // finished using it.
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

From source file:foam.starwisp.NetworkManager.java

public List<String> PostFile(String requestURL, File uploadFile) throws IOException {

    // creates a unique boundary based on time stamp
    String boundary = "===" + System.currentTimeMillis() + "===";

    URL url = new URL(requestURL);
    HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
    httpConn.setUseCaches(false);//from ww w  .j ava  2  s . c om
    httpConn.setDoOutput(true); // indicates POST method
    httpConn.setDoInput(true);
    httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
    httpConn.setRequestProperty("User-Agent", "CodeJava Agent");
    httpConn.setRequestProperty("Test", "Bonjour");
    OutputStream outputStream = httpConn.getOutputStream();
    PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream, "UTF-8"), true);

    String fileName = uploadFile.getName();
    writer.append("--" + boundary).append(LINE_FEED);
    writer.append("Content-Disposition: form-data; name=\"binary\";" + "filename=\"" + fileName + "\"")
            .append(LINE_FEED);
    writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(fileName)).append(LINE_FEED);
    writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
    writer.append(LINE_FEED);
    writer.flush();

    FileInputStream inputStream = new FileInputStream(uploadFile);
    byte[] buffer = new byte[4096];
    int bytesRead = -1;
    while ((bytesRead = inputStream.read(buffer)) != -1) {
        outputStream.write(buffer, 0, bytesRead);
    }
    outputStream.flush();
    inputStream.close();

    writer.append(LINE_FEED);
    writer.flush();

    List<String> response = new ArrayList<String>();

    writer.append(LINE_FEED).flush();
    writer.append("--" + boundary + "--").append(LINE_FEED);
    writer.close();

    // checks server's status code first
    int status = httpConn.getResponseCode();
    if (status == HttpURLConnection.HTTP_OK) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
        String line = null;
        while ((line = reader.readLine()) != null) {
            response.add(line);
        }
        reader.close();
        httpConn.disconnect();
    } else {
        throw new IOException("Server returned non-OK status: " + status);
    }

    return response;
}