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:crow.util.Util.java

public static String urlPost(HttpURLConnection conn, String encodePostParam) throws IOException {
    int responseCode = -1;
    OutputStream osw = null;//from ww  w.  j  a va  2  s  .c o m
    try {
        conn.setConnectTimeout(20000);
        conn.setReadTimeout(12000);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setDoOutput(true);
        byte[] bytes = encodePostParam.getBytes("UTF-8");
        conn.setRequestProperty("Content-Length", Integer.toString(bytes.length));
        osw = conn.getOutputStream();
        osw.write(bytes);
        osw.flush();
        responseCode = conn.getResponseCode();
        if (responseCode != HttpURLConnection.HTTP_OK) {
            throw new IOException("");
        } else {
            String s = inputStreamToString(conn.getInputStream());
            return s;
        }
    } finally {
        try {
            if (osw != null)
                osw.close();
        } catch (Exception ignore) {
        }
    }
}

From source file:com.magnet.plugin.common.helpers.URLHelper.java

public static String checkURLConnection(String urlS, String username, String password) {
    String status = "Error connection to server!";
    FormattedLogger logger = new FormattedLogger(URLHelper.class);
    logger.append("checkURLConnection:" + urlS);
    try {//  w ww.j a v a2  s . c  o m
        URL url = new URL(urlS);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        if (username != null && username.trim().length() > 0 && password != null
                && password.trim().length() > 0) {
            final String authString = username + ":" + password;
            conn.setRequestProperty("Authorization", "Basic " + Base64.encode(authString.getBytes()));
        }

        conn.setRequestMethod("GET");
        conn.setDoInput(true);

        status = "" + conn.getResponseCode();
        logger.append("Response code:" + status);
        logger.showInfoLog();
    } catch (Exception e) {
        logger.append(">>>" + e.getClass().getName() + " message: " + e.getMessage());
        logger.showErrorLog();
    }
    return status;
}

From source file:edu.gmu.csiss.automation.pacs.utils.BaseTool.java

/**
 * send a HTTP POST request// w  w w .jav  a 2 s . c  om
 * @param param
 * @param input_url
 * @return
 */
public static String POST(String param, String input_url) {
    try {
        URL url = new URL(input_url);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setDoOutput(true);
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-Type", "application/xml");
        con.setDoOutput(true);
        con.setDoInput(true);
        con.setUseCaches(false);

        PrintWriter xmlOut = new PrintWriter(con.getOutputStream());
        xmlOut.write(param);
        xmlOut.flush();
        BufferedReader response = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String result = "";
        String line;
        while ((line = response.readLine()) != null) {
            result += "\n" + line;
        }
        return result.toString();
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:eu.geopaparazzi.library.network.NetworkUtilities.java

/**
 * Sends an HTTP GET request to a url//from  w ww.  j  a  v  a 2  s. c  om
 *
 * @param urlStr - The URL of the server. (Example: " http://www.yahoo.com/search")
 * @param file the output file. If it is a folder, it tries to get the file name from the header.
 * @param requestParameters - all the request parameters (Example: "param1=val1&param2=val2"). 
 *           Note: This method will add the question mark (?) to the request - 
 *           DO NOT add it yourself
 * @param user
 * @param password
 * @return the file written. 
 * @throws Exception 
 */
public static File sendGetRequest4File(String urlStr, File file, String requestParameters, String user,
        String password) throws Exception {
    if (requestParameters != null && requestParameters.length() > 0) {
        urlStr += "?" + requestParameters;
    }
    HttpURLConnection conn = makeNewConnection(urlStr);
    conn.setRequestMethod("GET");
    // conn.setDoOutput(true);
    conn.setDoInput(true);
    // conn.setChunkedStreamingMode(0);
    conn.setUseCaches(false);

    if (user != null && password != null) {
        conn.setRequestProperty("Authorization", getB64Auth(user, password));
    }
    conn.connect();

    if (file.isDirectory()) {
        // try to get the header
        String headerField = conn.getHeaderField("Content-Disposition");
        String fileName = null;
        if (headerField != null) {
            String[] split = headerField.split(";");
            for (String string : split) {
                String pattern = "filename=";
                if (string.toLowerCase().startsWith(pattern)) {
                    fileName = string.replaceFirst(pattern, "");
                    break;
                }
            }
        }
        if (fileName == null) {
            // give a name
            fileName = "FILE_" + LibraryConstants.TIMESTAMPFORMATTER.format(new Date());
        }
        file = new File(file, fileName);
    }

    InputStream in = null;
    FileOutputStream out = null;
    try {
        in = conn.getInputStream();
        out = new FileOutputStream(file);

        byte[] buffer = new byte[(int) maxBufferSize];
        int bytesRead = in.read(buffer, 0, (int) maxBufferSize);
        while (bytesRead > 0) {
            out.write(buffer, 0, bytesRead);
            bytesRead = in.read(buffer, 0, (int) maxBufferSize);
        }
        out.flush();

    } finally {
        if (in != null)
            in.close();
        if (out != null)
            out.close();
    }
    return file;
}

From source file:com.entertailion.android.slideshow.utils.Utils.java

/**
 * Create a bitmap from a image URL./*w  w w  .  j av  a 2s  .c o  m*/
 * 
 * @param src
 * @return
 */
public static final Bitmap getBitmapFromURL(String src) {
    try {
        URL url = new URL(src);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        int size = Math.max(myBitmap.getWidth(), myBitmap.getHeight());
        Bitmap b = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(b);
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        c.drawBitmap(myBitmap, (size - myBitmap.getWidth()) / 2, (size - myBitmap.getHeight()) / 2, paint);
        return b;
    } catch (Exception e) {
        Log.e(LOG_TAG, "Faild to get the image from URL:" + src, e);
        return null;
    }
}

From source file:com.wisdombud.right.client.common.HttpKit.java

private static HttpURLConnection getHttpConnection(String url, String method, Map<String, String> headers)
        throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
    final URL _url = new URL(url);
    final HttpURLConnection conn = (HttpURLConnection) _url.openConnection();
    if (conn instanceof HttpsURLConnection) {
        ((HttpsURLConnection) conn).setSSLSocketFactory(sslSocketFactory);
        ((HttpsURLConnection) conn).setHostnameVerifier(trustAnyHostnameVerifier);
    }//w w  w .j a  v  a  2  s .c  o  m

    conn.setRequestMethod(method);
    conn.setDoOutput(true);
    conn.setDoInput(true);

    conn.setConnectTimeout(19000);
    conn.setReadTimeout(19000);

    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setRequestProperty("User-Agent",
            "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");

    if (headers != null && !headers.isEmpty()) {
        for (final Entry<String, String> entry : headers.entrySet()) {
            conn.setRequestProperty(entry.getKey(), entry.getValue());
        }
    }

    return conn;
}

From source file:eu.liveandgov.ar.utilities.Download_Data.java

/**                      DownAndCopy
 * /* w w  w. j  a  v a2 s  . c o  m*/
 * Download file from URL and Copy to Android file system folder
 * 
 * @param fileUrl
 * @param StringAndroidPath
 */
public static boolean DownAndCopy(String fileUrlSTR, String StringAndroidPath, boolean preservefilename,
        String Caller) {

    if (compareRemoteWithLocal(fileUrlSTR, StringAndroidPath)) {
        //Log.e("fileUrlSTR", "SKIP WITH HASH");
        return true;
    } else {
        Log.e("TRY TO DOWNLOAD BY " + Caller, fileUrlSTR);
    }

    SimpleDateFormat sdf = new SimpleDateFormat("mm");

    // Check if downloaded at least just 2 minutes ago
    for (String[] mem : MemDown)
        if (fileUrlSTR.equals(mem[0])) {
            int diff = Integer.parseInt(sdf.format(new Date())) - Integer.parseInt(mem[1]);
            Log.e("diff", " " + diff);
            if (diff < 2) {
                Log.d("Download_Data", "I am not downloading " + fileUrlSTR + " because it was downloaded "
                        + diff + " minutes ago");
                return true;
            }
        }

    if (!OS_Utils.exists(fileUrlSTR)) {
        Log.e("Download_Data", "URL: " + fileUrlSTR + " called from " + Caller + " not exists to copy it to "
                + StringAndroidPath);
        return false;
    }

    int DEBUG_FLAG = 0;

    HttpURLConnection conn;
    URL fileUrl = null;
    try {
        fileUrl = new URL(fileUrlSTR);
    } catch (MalformedURLException e1) {
        return false;
    }

    try {
        conn = (HttpURLConnection) fileUrl.openConnection();

        DEBUG_FLAG = 1;

        conn.setDoInput(true);
        conn.connect();
        InputStream is = conn.getInputStream();
        BufferedInputStream bis = new BufferedInputStream(is);
        ByteArrayBuffer baf = new ByteArrayBuffer(100);

        DEBUG_FLAG = 2;

        int current = 0;
        byte[] buffer = new byte[10];
        while ((current = bis.read(buffer)) != -1)
            baf.append(buffer, 0, current);

        DEBUG_FLAG = 3;

        /* Convert the Bytes read to a String. */
        File fileAndroid;

        try {

            if (preservefilename) {
                int iSlash = fileUrlSTR.lastIndexOf("/");
                fileAndroid = new File(StringAndroidPath + "/" + fileUrlSTR.substring(iSlash + 1));
            } else
                fileAndroid = new File(StringAndroidPath);

        } catch (Exception e) {
            Log.e("Download_Data.DownAndCopy", "I can not create " + StringAndroidPath);
            bis.close();
            conn.disconnect();
            return false;
        }

        DEBUG_FLAG = 4;

        FileOutputStream fos = new FileOutputStream(fileAndroid);
        fos.write(baf.toByteArray());

        DEBUG_FLAG = 5;

        bis.close();
        fos.close();
        conn.disconnect();

        MemDown.add(new String[] { fileUrlSTR, sdf.format(new Date()) });

        return true; //returns including the filename
    } catch (IOException e) {
        Log.e("Download_Data", "Download_Data: Error when trying to download:  " + fileUrl.toString() + " to "
                + StringAndroidPath + " DEBUG_FLAG=" + DEBUG_FLAG);
        return false;
    }

}

From source file:com.futureplatforms.kirin.internal.attic.IOUtils.java

public static InputStream postConnection(Context context, URL url, String method, String urlParameters)
        throws IOException {
    if (!url.getProtocol().startsWith("http")) {
        return url.openStream();
    }//from  ww w  .  j  a  v a  2  s. c  om

    URLConnection c = url.openConnection();

    HttpURLConnection connection = (HttpURLConnection) c;

    connection.setRequestMethod(method.toUpperCase());
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

    connection.setRequestProperty("Content-Length", "" + Integer.toString(urlParameters.getBytes().length));
    connection.setRequestProperty("Content-Language", "en-US");

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

    OutputStream output = null;
    try {
        output = connection.getOutputStream();
        output.write(urlParameters.getBytes("UTF-8"));
        output.flush();
    } finally {
        IOUtils.close(output);
    }
    return connection.getInputStream();
}

From source file:eu.geopaparazzi.library.network.NetworkUtilities.java

/**
 * Sends a string via POST to a given url.
 * // w  w w.j  a v a  2s  .c om
 * @param urlStr the url to which to send to.
 * @param string the string to send as post body.
 * @param user the user or <code>null</code>.
 * @param password the password or <code>null</code>.
 * @return the response.
 * @throws Exception
 */
public static String sendPost(String urlStr, String string, String user, String password) throws Exception {
    BufferedOutputStream wr = null;
    HttpURLConnection conn = null;
    try {
        conn = makeNewConnection(urlStr);
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);
        conn.setDoInput(true);
        // conn.setChunkedStreamingMode(0);
        conn.setUseCaches(false);
        if (user != null && password != null) {
            conn.setRequestProperty("Authorization", getB64Auth(user, password));
        }
        conn.connect();

        // Make server believe we are form data...
        wr = new BufferedOutputStream(conn.getOutputStream());
        byte[] bytes = string.getBytes();
        wr.write(bytes);
        wr.flush();

        int responseCode = conn.getResponseCode();
        StringBuilder returnMessageBuilder = new StringBuilder();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            while (true) {
                String line = br.readLine();
                if (line == null)
                    break;
                returnMessageBuilder.append(line + "\n");
            }
            br.close();
        }

        return returnMessageBuilder.toString();
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    } finally {
        if (conn != null)
            conn.disconnect();
    }
}

From source file:org.grameenfoundation.consulteca.utils.HttpHelpers.java

/**
 * Does an HTTP post for a given form data string.
 *
 * @param data is the form data string./*from  w  w w . j av a2 s .  c  o  m*/
 * @param url  is the url to post to.
 * @return the return string from the server.
 * @throws java.io.IOException
 */
public static String postData(String data, URL url) throws IOException {

    String result = null;

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

    try {
        HttpHelpers.addCommonHeaders(conn);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setConnectTimeout(HttpHelpers.NETWORK_TIMEOUT);
        conn.setReadTimeout(HttpHelpers.NETWORK_TIMEOUT);
        conn.setRequestProperty("Content-Length", "" + Integer.toString(data.getBytes().length));

        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

        writer.write(data);
        writer.flush();
        writer.close();

        String line;
        BufferedReader reader = (BufferedReader) getUncompressedResponseReader(conn);
        while ((line = reader.readLine()) != null) {
            if (result == null)
                result = line;
            else
                result += line;
        }

        reader.close();
    } catch (IOException ex) {
        Log.e(TAG, "Failed to read stream data", ex);

        String error = null;

        // TODO Am not yet sure if the section below should make it in the production release.
        // I mainly use it to get details of a failed http request. I get a FileNotFoundException
        // when actually the url is correct but an exception was thrown at the server and i use this
        // to get the server call stack for debugging purposes.
        try {
            String line;
            BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
            while ((line = reader.readLine()) != null) {
                if (error == null)
                    error = line;
                else
                    error += line;
            }

            reader.close();
        } catch (Exception e) {
            Log.e(TAG, "Problem encountered while trying to get error information:" + error, ex);
        }
    }

    return result;
}