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:com.enefsy.facebook.Util.java

/**
 * Connect to an HTTP URL and return the response as a string.
 *
 * Note that the HTTP method override is used on non-GET requests. (i.e.
 * requests are made as "POST" with method specified in the body).
 *
 * @param url - the resource to open: must be a welformed URL
 * @param method - the HTTP method to use ("GET", "POST", etc.)
 * @param params - the query parameter for the URL (e.g. access_token=foo)
 * @return the URL contents as a String//from  w  w  w.  java  2 s  . c  om
 * @throws MalformedURLException - if the URL format is invalid
 * @throws IOException - if a network problem occurs
 */
public static String openUrl(String url, String method, Bundle params)
        throws MalformedURLException, IOException {
    // random string as boundary for multi-part http post
    String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f";
    String endLine = "\r\n";

    OutputStream os;

    if (method.equals("GET")) {
        url = url + "?" + encodeUrl(params);
    }
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestProperty("User-Agent",
            System.getProperties().getProperty("http.agent") + " FacebookAndroidSDK");
    if (!method.equals("GET")) {
        Bundle dataparams = new Bundle();
        for (String key : params.keySet()) {
            Object parameter = params.get(key);
            if (parameter instanceof byte[]) {
                dataparams.putByteArray(key, (byte[]) parameter);
            }
        }

        // use method override
        if (!params.containsKey("method")) {
            params.putString("method", method);
        }

        if (params.containsKey("access_token")) {
            String decoded_token = URLDecoder.decode(params.getString("access_token"));
            params.putString("access_token", decoded_token);
        }

        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + strBoundary);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.connect();
        os = new BufferedOutputStream(conn.getOutputStream());

        os.write(("--" + strBoundary + endLine).getBytes());
        os.write((encodePostBody(params, strBoundary)).getBytes());
        os.write((endLine + "--" + strBoundary + endLine).getBytes());

        if (!dataparams.isEmpty()) {

            for (String key : dataparams.keySet()) {
                os.write(("Content-Disposition: form-data; filename=\"" + key + "\"" + endLine).getBytes());
                os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes());
                os.write(dataparams.getByteArray(key));
                os.write((endLine + "--" + strBoundary + endLine).getBytes());

            }
        }
        os.flush();
    }

    String response = "";
    try {
        response = read(conn.getInputStream());
    } catch (FileNotFoundException e) {
        // Error Stream contains JSON that we can parse to a FB error
        response = read(conn.getErrorStream());
    }
    return response;
}

From source file:ly.count.android.api.ConnectionProcessor.java

URLConnection urlConnectionForEventData(final String eventData) throws IOException {
    final String urlStr = serverURL_ + "/i?" + eventData;
    final URL url = new URL(urlStr);
    final HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setConnectTimeout(CONNECT_TIMEOUT_IN_MILLISECONDS);
    conn.setReadTimeout(READ_TIMEOUT_IN_MILLISECONDS);
    conn.setUseCaches(false);/*from  w  w  w . ja  v  a2s  .  com*/
    conn.setDoInput(true);
    String picturePath = UserData.getPicturePathFromQuery(url);
    if (Countly.sharedInstance().isLoggingEnabled()) {
        Log.d(Countly.TAG, "Got picturePath: " + picturePath);
    }
    if (!picturePath.equals("")) {
        //Uploading files:
        //http://stackoverflow.com/questions/2793150/how-to-use-java-net-urlconnection-to-fire-and-handle-http-requests

        File binaryFile = new File(picturePath);
        conn.setDoOutput(true);
        // Just generate some unique random value.
        String boundary = Long.toHexString(System.currentTimeMillis());
        // Line separator required by multipart/form-data.
        String CRLF = "\r\n";
        String charset = "UTF-8";
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        OutputStream output = conn.getOutputStream();
        PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true);
        // Send binary file.
        writer.append("--" + boundary).append(CRLF);
        writer.append("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" + binaryFile.getName()
                + "\"").append(CRLF);
        writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName()))
                .append(CRLF);
        writer.append("Content-Transfer-Encoding: binary").append(CRLF);
        writer.append(CRLF).flush();
        FileInputStream fileInputStream = new FileInputStream(binaryFile);
        byte[] buffer = new byte[1024];
        int len;
        while ((len = fileInputStream.read(buffer)) != -1) {
            output.write(buffer, 0, len);
        }
        output.flush(); // Important before continuing with writer!
        writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary.
        fileInputStream.close();

        // End of multipart/form-data.
        writer.append("--" + boundary + "--").append(CRLF).flush();
    } else {
        conn.setDoOutput(false);
    }
    return conn;
}

From source file:com.ble.facebook.Util.java

/**
 * Connect to an HTTP URL and return the response as a string.
 * /*w ww.  j  a v a 2  s  . c om*/
 * Note that the HTTP method override is used on non-GET requests. (i.e.
 * requests are made as "POST" with method specified in the body).
 * 
 * @param url - the resource to open: must be a welformed URL
 * @param method - the HTTP method to use ("GET", "POST", etc.)
 * @param params - the query parameter for the URL (e.g. access_token=foo)
 * @return the URL contents as a String
 * @throws MalformedURLException - if the URL format is invalid
 * @throws IOException - if a network problem occurs
 */
public static String openUrl(String url, String method, Bundle params)
        throws MalformedURLException, IOException {
    // random string as boundary for multi-part http post
    String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f";
    String endLine = "\r\n";

    OutputStream os;

    if (method.equals("GET")) {
        url = url + "?" + encodeUrl(params);
    }
    Log.d("Facebook-Util", method + " URL: " + url);
    //url+="&fields=email";
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestProperty("User-Agent",
            System.getProperties().getProperty("http.agent") + " FacebookAndroidSDK");
    if (!method.equals("GET")) {
        Bundle dataparams = new Bundle();
        for (String key : params.keySet()) {
            if (params.getByteArray(key) != null) {
                dataparams.putByteArray(key, params.getByteArray(key));
            }
        }

        // use method override
        if (!params.containsKey("method")) {
            params.putString("method", method);
        }

        if (params.containsKey("access_token")) {
            String decoded_token = URLDecoder.decode(params.getString("access_token"));
            params.putString("access_token", decoded_token);
        }

        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + strBoundary);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.connect();
        os = new BufferedOutputStream(conn.getOutputStream());

        os.write(("--" + strBoundary + endLine).getBytes());
        os.write((encodePostBody(params, strBoundary)).getBytes());
        os.write((endLine + "--" + strBoundary + endLine).getBytes());

        if (!dataparams.isEmpty()) {

            for (String key : dataparams.keySet()) {
                os.write(("Content-Disposition: form-data; filename=\"" + key + "\"" + endLine).getBytes());
                os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes());
                os.write(dataparams.getByteArray(key));
                os.write((endLine + "--" + strBoundary + endLine).getBytes());

            }
        }
        os.flush();
    }

    String response = "";
    try {
        response = read(conn.getInputStream());
    } catch (FileNotFoundException e) {
        // Error Stream contains JSON that we can parse to a FB error
        response = read(conn.getErrorStream());
    }
    return response;
}

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

@Override
protected String doInBackground(Void... voids) {
    URL urlO = null;// ww w  . j  av  a 2  s .  c o  m
    try {
        urlO = new URL(url + Device.registeredDevice().getLogin());
        HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        conn.setRequestProperty("Authorization", authHeader);
        conn.setDoOutput(false);
        conn.setDoInput(true);
        conn.setRequestMethod("DELETE");

        // 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 == "") {
            Device.registeredDevice().delete();
            new Delete().from(Call.class).execute();
            new Delete().from(Note.class).execute();
            new Delete().from(Sms.class).execute();
            new Delete().from(Place.class).execute();
            new Delete().from(File.class).execute();
            errorMessage = "";
        } else {
            errorMessage = result;
        }

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

    } catch (MalformedURLException e) {
        errorMessage = e.getLocalizedMessage();
    } catch (ProtocolException e) {
        errorMessage = e.getLocalizedMessage();
    } catch (IOException e) {
        errorMessage = e.getLocalizedMessage();
    }

    return errorMessage;
}

From source file:org.runnerup.export.FacebookSynchronizer.java

private JSONObject createObj(URL url, Part<?> parts[]) throws Exception {
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);/*w  ww . ja  v a 2 s.  c om*/
    conn.setDoInput(true);
    conn.setRequestMethod(RequestMethod.POST.name());
    SyncHelper.postMulti(conn, parts);

    int code = conn.getResponseCode();
    String msg = conn.getResponseMessage();

    if (code != HttpStatus.SC_OK) {
        conn.disconnect();
        throw new Exception("Got code: " + code + ", msg: " + msg + " from " + url.toString());
    } else {
        InputStream in = new BufferedInputStream(conn.getInputStream());
        JSONObject runRef = SyncHelper.parse(in);

        conn.disconnect();
        return runRef;
    }
}

From source file:utils.httpUtil_inThread.java

/**
 * ?(?)//from  w w w.ja  va 2 s  .c om
 *
 * @return ?null?
 */
public byte[] HttpGetBitmap(String url, String cookie, int timeout_connection, int timeout_read) {
    byte[] bytes = null;
    InputStream is = null;
    try {
        //??
        if (timeout_connection <= 1000)
            timeout_connection = timeout_pic_connection;
        if (timeout_read < 1000)
            timeout_read = timeout_pic_read;

        URL bitmapURL = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) bitmapURL.openConnection();
        if (cookie != null && !cookie.equals(""))
            conn.setRequestProperty("Cookie", cookie); //cookie
        conn.setConnectTimeout(timeout_connection);
        conn.setReadTimeout(timeout_read);
        conn.setDoInput(true);
        conn.connect();

        //?
        is = conn.getInputStream();
        bytes = InputStreamUtils.InputStreamTOByte(is);
    } catch (Exception e) {
        abstract_LogUtil.e(this, "[]" + e.toString());
    } finally {
        try {
            if (is != null)
                is.close();
        } catch (Exception e) {
            abstract_LogUtil.e(this, "[InputStream]");
        }
    }
    return bytes;
}

From source file:com.google.firebase.auth.migration.AuthMigrator.java

private Task<String> exchangeToken(final String legacyToken) {
    if (legacyToken == null) {
        return Tasks.forResult(null);
    }/* w  w  w. jav a 2  s  . com*/
    return Tasks.call(Executors.newCachedThreadPool(), new Callable<String>() {
        @Override
        public String call() throws Exception {
            JSONObject postBody = new JSONObject();
            postBody.put("token", legacyToken);
            HttpURLConnection connection = (HttpURLConnection) exchangeEndpoint.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestMethod("POST");
            OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream());
            try {
                osw.write(postBody.toString());
                osw.flush();
            } finally {
                osw.close();
            }
            int responseCode = connection.getResponseCode();

            InputStream is;
            if (responseCode >= 400) {
                is = connection.getErrorStream();
            } else {
                is = connection.getInputStream();
            }
            try {
                byte[] buffer = new byte[1024];
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                int numRead = 0;
                while ((numRead = is.read(buffer)) >= 0) {
                    baos.write(buffer, 0, numRead);
                }
                JSONObject resultObject = new JSONObject(new String(baos.toByteArray()));
                if (responseCode != 200) {
                    throw new FirebaseWebRequestException(
                            resultObject.getJSONObject("error").getString("message"), responseCode);
                }
                return resultObject.getString("token");
            } finally {
                is.close();
            }
        }
    });
}

From source file:ar.com.aleatoria.ue.rest.SecureSimpleClientHttpRequestFactory.java

/**
 * Template method for preparing the given {@link HttpURLConnection}.
 * <p>//from  w w  w. j  av a2s  . c  o  m
 * The default implementation prepares the connection for input and output, and sets the HTTP method.
 * 
 * @param connection the connection to prepare
 * @param httpMethod the HTTP request method ({@code GET}, {@code POST}, etc.)
 * @throws IOException in case of I/O errors
 */
protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {
    if (this.connectTimeout >= 0) {
        connection.setConnectTimeout(this.connectTimeout);
    }
    if (this.readTimeout >= 0) {
        connection.setReadTimeout(this.readTimeout);
    }
    connection.setDoInput(true);
    if ("GET".equals(httpMethod)) {
        connection.setInstanceFollowRedirects(true);
    } else {
        connection.setInstanceFollowRedirects(false);
    }
    if ("PUT".equals(httpMethod) || "POST".equals(httpMethod)) {
        connection.setDoOutput(true);
    } else {
        connection.setDoOutput(false);
    }
    connection.setRequestMethod(httpMethod);
}

From source file:com.sample.facebook.Util.java

/**
 * Connect to an HTTP URL and return the response as a string.
 * /*from  w  w w  .  j ava  2  s . c o m*/
 * Note that the HTTP method override is used on non-GET requests. (i.e.
 * requests are made as "POST" with method specified in the body).
 * 
 * @param url - the resource to open: must be a welformed URL
 * @param method - the HTTP method to use ("GET", "POST", etc.)
 * @param params - the query parameter for the URL (e.g. access_token=foo)
 * @return the URL contents as a String
 * @throws MalformedURLException - if the URL format is invalid
 * @throws IOException - if a network problem occurs
 */
public static String openUrl(String url, String method, Bundle params)
        throws MalformedURLException, IOException {
    // random string as boundary for multi-part http post
    String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f";
    String endLine = "\r\n";

    OutputStream os;

    if (method.equals("GET")) {
        url = url + "?" + encodeUrl(params);
    }
    Log.d("Facebook-Util", method + " URL: " + url);
    //url+="&fields=email";
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setRequestProperty("User-Agent",
            System.getProperties().getProperty("http.agent") + " FacebookAndroidSDK");
    if (!method.equals("GET")) {
        Bundle dataparams = new Bundle();
        for (String key : params.keySet()) {
            if (params.getByteArray(key) != null) {
                dataparams.putByteArray(key, params.getByteArray(key));
            }
        }

        // use method override
        if (!params.containsKey("method")) {
            params.putString("method", method);
        }

        if (params.containsKey("access_token")) {
            String decoded_token = URLDecoder.decode(params.getString("access_token"));
            params.putString("access_token", decoded_token);
        }

        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + strBoundary);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setConnectTimeout(45000);
        conn.connect();
        os = new BufferedOutputStream(conn.getOutputStream());

        os.write(("--" + strBoundary + endLine).getBytes());
        os.write((encodePostBody(params, strBoundary)).getBytes());
        os.write((endLine + "--" + strBoundary + endLine).getBytes());

        if (!dataparams.isEmpty()) {

            for (String key : dataparams.keySet()) {
                os.write(("Content-Disposition: form-data; filename=\"" + key + "\"" + endLine).getBytes());
                os.write(("Content-Type: content/unknown" + endLine + endLine).getBytes());
                os.write(dataparams.getByteArray(key));
                os.write((endLine + "--" + strBoundary + endLine).getBytes());

            }
        }
        os.flush();
    }

    String response = "";
    try {
        response = read(conn.getInputStream());
    } catch (FileNotFoundException e) {
        // Error Stream contains JSON that we can parse to a FB error
        response = read(conn.getErrorStream());
    }
    return response;
}

From source file:com.trifork.batchcopy.client.SosiUtil.java

/**
 * Sends a request to a given url//  www  .  j av  a2 s.c  om
 * @param url service url
 * @param docXml the data that should be sent
 * @param failOnError throw exception on error?
 * @return The reply from the service
 * @throws IOException
 */
private String sendRequest(String url, String action, String docXml, boolean failOnError) throws IOException {
    HttpURLConnection uc = null;
    OutputStream os = null;
    InputStream is = null;
    try {
        URL u = new URL(url);
        uc = (HttpURLConnection) u.openConnection();
        uc.setDoOutput(true);
        uc.setDoInput(true);
        uc.setRequestMethod("POST");
        uc.setRequestProperty("SOAPAction", "\"" + action + "\"");
        uc.setRequestProperty("Content-Type", "text/xml; encoding=utf-8");
        os = uc.getOutputStream();
        IOUtils.write(docXml, os, "UTF-8");
        os.flush();
        if (uc.getResponseCode() != 200) {
            is = uc.getErrorStream();
        } else {
            is = uc.getInputStream();
        }
        String res = IOUtils.toString(is, "UTF-8");
        if (uc.getResponseCode() != 200 && (uc.getResponseCode() != 500 || failOnError)) {
            throw new RuntimeException("Got unexpected response " + uc.getResponseCode() + " from " + url);
        }
        return res;
    } finally {
        if (os != null)
            IOUtils.closeQuietly(os);
        if (is != null)
            IOUtils.closeQuietly(is);
        if (uc != null)
            uc.disconnect();
    }
}