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:de.appplant.cordova.plugin.notification.Asset.java

/**
 *Get Uri for HTTP Content//from  www .  j  a  va 2s. co m
 * @param path HTTP adress
 * @return Uri of the downloaded file
 */
private Uri getUriForHTTP(String path) {
    try {
        URL url = new URL(path);
        String fileName = path.substring(path.lastIndexOf('/') + 1);
        String resName = fileName.substring(0, fileName.lastIndexOf('.'));
        String extension = path.substring(path.lastIndexOf('.'));
        File dir = activity.getExternalCacheDir();
        if (dir == null) {
            Log.e("Asset", "Missing external cache dir");
            return Uri.EMPTY;
        }
        String storage = dir.toString() + STORAGE_FOLDER;
        File file = new File(storage, resName + extension);
        new File(storage).mkdir();

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();

        StrictMode.setThreadPolicy(policy);

        connection.setDoInput(true);
        connection.connect();

        InputStream input = connection.getInputStream();
        FileOutputStream outStream = new FileOutputStream(file);
        copyFile(input, outStream);
        outStream.flush();
        outStream.close();

        return Uri.fromFile(file);
    } catch (MalformedURLException e) {
        Log.e("Asset", "Incorrect URL");
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        Log.e("Asset", "Failed to create new File from HTTP Content");
        e.printStackTrace();
    } catch (IOException e) {
        Log.e("Asset", "No Input can be created from http Stream");
        e.printStackTrace();
    }
    return Uri.EMPTY;
}

From source file:com.cisco.gerrit.plugins.slack.client.WebhookClient.java

/**
 * Initiates an HTTP POST to the provided Webhook URL.
 *
 * @param message The message payload.// w w  w .ja  v a  2s  .co  m
 * @param webhookUrl The URL to post to.
 * @return The response payload from Slack.
 */
private String postRequest(String message, String webhookUrl) {
    String response;

    HttpURLConnection connection;
    connection = null;
    try {
        connection = openConnection(webhookUrl);
        try {
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("charset", "utf-8");

            connection.setDoInput(true);
            connection.setDoOutput(true);

            DataOutputStream request;
            request = new DataOutputStream(connection.getOutputStream());

            request.write(message.getBytes(StandardCharsets.UTF_8));
            request.flush();
            request.close();
        } catch (IOException e) {
            throw new RuntimeException("Error posting message to Slack: [" + e.getMessage() + "].", e);
        }

        response = getResponse(connection);
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
    }

    return response;
}

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

@Override
protected String doInBackground(String... docTypes) {
    errorMessage = "";
    for (int i = 0; i < docTypes.length; i++) {
        String docType = docTypes[i].toLowerCase();
        publishProgress("Checking design: " + docType);

        URL urlO = null;//from www  .  j  a va2 s .  c  o  m
        try {

            // using all view can break notes, files app in cozy
            urlO = getCosiUrl(docType);

            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();

            if (result != "") {
                errorMessage = createDesignDocument(docType);
                if (errorMessage != "") {
                    return errorMessage;
                } else {
                    errorMessage = "";
                }
            } else {
                errorMessage = "Failed to parse API response";
                return errorMessage;
            }

            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();
        }
    }

    return errorMessage;
}

From source file:com.mercandalli.android.apps.files.common.net.TaskGet.java

@Override
protected String doInBackground(Void... urls) {
    try {/*from w  w  w  .  j a va 2 s  . c  o m*/
        if (this.parameters != null) {
            if (!StringUtils.isNullOrEmpty(Config.getNotificationId())) {
                parameters.add(new StringPair("android_id", "" + Config.getNotificationId()));
            }
            url = NetUtils.addUrlParameters(url, parameters);
        }

        Log.d("TaskGet", "url = " + url);

        URL tmp_url = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) tmp_url.openConnection();
        conn.setReadTimeout(10_000);
        conn.setConnectTimeout(15_000);
        conn.setRequestMethod("GET");
        if (isAuthentication) {
            conn.setRequestProperty("Authorization", "Basic " + Config.getUserToken());
        }
        conn.setUseCaches(false);
        conn.setDoInput(true);

        conn.connect(); // Starts the query
        int responseCode = conn.getResponseCode();
        InputStream inputStream = new BufferedInputStream(conn.getInputStream());

        // convert inputstream to string
        String resultString = convertInputStreamToString(inputStream);

        //int responseCode = response.getStatusLine().getStatusCode();
        if (responseCode >= 300) {
            resultString = "Status Code " + responseCode + ". " + resultString;
        }

        conn.disconnect();

        return resultString;
    } catch (IOException e) {
        Log.e(getClass().getName(), "IOException", e);
    }
    return null;
}

From source file:com.zjut.material_wecenter.Client.java

/**
 * doPost ??POST//from  w  w w .j a v a  2 s .  c o  m
 * @param URL URL
 * @param params ?
 * @return ?NULL
 */
private String doPost(String URL, Map<String, String> params) {
    // 
    StringBuilder builder = new StringBuilder();
    for (Map.Entry<String, String> entry : params.entrySet()) {
        builder.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue())).append("&");
    }
    builder.deleteCharAt(builder.length() - 1);
    byte[] data = builder.toString().getBytes();
    // ?
    try {
        URL url = new URL(URL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(Config.TIME_OUT);
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setUseCaches(false);
        // Cookie
        connection.setRequestProperty("Cookie", cooike);
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("Content-Length", String.valueOf(data.length));
        // ??
        OutputStream output = connection.getOutputStream();
        output.write(data);
        // ?
        int response = connection.getResponseCode();
        if (response == HttpURLConnection.HTTP_OK) {
            // ?Cookie
            Map<String, List<String>> header = connection.getHeaderFields();
            List<String> cookies = header.get("Set-Cookie");
            if (cookies.size() == 3)
                cooike = cookies.get(2);
            // ??
            InputStream input = connection.getInputStream();
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[Config.MAX_LINE_BUFFER];
            int len = 0;
            while ((len = input.read(buffer)) != -1)
                byteArrayOutputStream.write(buffer, 0, len);
            return new String(byteArrayOutputStream.toByteArray());
        }
    } catch (IOException e) {
        return null;
    }
    return null;
}

From source file:com.pursuer.reader.easyrss.network.NetworkClient.java

public InputStream doPostStream(final String url, final String params) throws IOException, NetworkException {
    final HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setConnectTimeout(40 * 1000);//from ww w. j  av  a  2s .  co  m
    conn.setReadTimeout(30 * 1000);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    if (auth != null) {
        conn.setRequestProperty("Authorization", "GoogleLogin auth=" + auth);
    }
    conn.setDoInput(true);
    conn.setDoOutput(true);
    final OutputStream output = conn.getOutputStream();
    output.write(params.getBytes());
    output.flush();
    output.close();

    conn.connect();
    try {
        final int resStatus = conn.getResponseCode();
        if (resStatus == HttpStatus.SC_UNAUTHORIZED) {
            ReaderAccountMgr.getInstance().invalidateAuth();
        }
        if (resStatus != HttpStatus.SC_OK) {
            throw new NetworkException("Invalid HTTP status " + resStatus + ": " + url + ".");
        }
    } catch (final IOException exception) {
        if (exception.getMessage() != null && exception.getMessage().contains("authentication")) {
            ReaderAccountMgr.getInstance().invalidateAuth();
        }
        throw exception;
    }
    return conn.getInputStream();
}

From source file:com.theisleoffavalon.mcmanager.mobile.RestClient.java

/**
 * Sends a JSONRPC request//from w  w w .  j  a v a  2  s .  com
 * 
 * @param request
 *            The request to send
 * @return The response
 */
private JSONObject sendJSONRPC(JSONObject request) {
    JSONObject ret = null;

    try {
        HttpURLConnection conn = (HttpURLConnection) this.rootUrl.openConnection();
        conn.setRequestMethod("POST");
        conn.setChunkedStreamingMode(0);
        conn.setDoInput(true);
        conn.setDoOutput(true);
        OutputStreamWriter osw = new OutputStreamWriter(new BufferedOutputStream(conn.getOutputStream()));
        request.writeJSONString(osw);
        osw.close();

        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            InputStreamReader isr = new InputStreamReader(new BufferedInputStream(conn.getInputStream()));
            ret = (JSONObject) new JSONParser().parse(isr);
        } else {
            Log.e("RestClient", String.format("Got %d instead of %d for HTTP Response", conn.getResponseCode(),
                    HttpURLConnection.HTTP_OK));
            return null;
        }

    } catch (IOException e) {
        Log.e("RestClient", "Error in sendJSONRPC", e);
    } catch (ParseException e) {
        Log.e("RestClient", "Parse return data error", e);
    }
    return ret;
}

From source file:com.jaredrummler.android.device.DeviceName.java

/** Download URL to String */
private static String downloadJson(String myurl) throws IOException {
    StringBuilder sb = new StringBuilder();
    BufferedReader reader = null;
    try {/*from  ww  w . j ava2 s .  c om*/
        URL url = new URL(myurl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000);
        conn.setConnectTimeout(15000);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        conn.connect();
        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line).append('\n');
            }
        }
        return sb.toString();
    } finally {
        if (reader != null) {
            reader.close();
        }
    }
}

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

private String createDesignDocument(String docType) {
    String returnResult = "";
    JSONObject docTypeMap = new JSONObject();
    try {/* w w w . j  a va 2 s  .  c o m*/
        docTypeMap.put("map", "function (doc) { if (doc.docType.toLowerCase() === '" + docType
                + "') { filter = function (doc) { return emit(doc._id, doc); }; filter(doc); }}");

        URL urlO = getCosiUrl(docType);

        String 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
        OutputStream os = conn.getOutputStream();
        os.write(docTypeMap.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();

        if (result.contains("success")) {
            returnResult = "";
        } else {
            returnResult = result;
        }

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

    } catch (UnsupportedEncodingException e) {
        returnResult = e.getLocalizedMessage();
        e.printStackTrace();
    } catch (ProtocolException e) {
        returnResult = e.getLocalizedMessage();
        e.printStackTrace();
    } catch (IOException e) {
        returnResult = e.getLocalizedMessage();
        e.printStackTrace();
    } catch (JSONException e) {
        returnResult = e.getLocalizedMessage();
        e.printStackTrace();
    }

    return returnResult;
}

From source file:com.example.socketmobile.android.warrantychecker.network.WarrantyCheck.java

private Object fetchWarranty(String id, String authString, String query) throws IOException {
    InputStream is = null;/*w  ww  .  ja  v  a 2 s. c om*/
    RegistrationApiResponse result = null;
    RegistrationApiErrorResponse errorResult = null;
    String authHeader = "Basic " + Base64.encodeToString(authString.getBytes(), Base64.NO_WRAP);

    try {
        URL url = new URL(baseUrl + id + "?" + query);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(10000 /* milliseconds */);
        //conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/json");
        conn.setRequestProperty("Authorization", authHeader);
        conn.setDoInput(true);
        conn.setDoOutput(false);

        conn.connect();
        int response = conn.getResponseCode();
        Log.d(TAG, "WarrantyCheck query responded: " + response);
        switch (response / 100) {
        case 2:
            is = conn.getInputStream();
            RegistrationApiResponse.Reader reader = new RegistrationApiResponse.Reader();
            result = reader.readJsonStream(is);
            break;
        case 4:
        case 5:
            is = conn.getErrorStream();
            RegistrationApiErrorResponse.Reader errorReader = new RegistrationApiErrorResponse.Reader();
            errorResult = errorReader.readErrorJsonStream(is);
            break;
        }

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        return null;
    } finally {
        if (is != null) {
            is.close();
        }
    }
    return (result != null) ? result : errorResult;
}