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.choices.imagecompare.urlsfetcher.ImageUrlsFetcher.java

@Nullable
private static String downloadContentAsString(String urlString) throws IOException {
    InputStream is = null;//from  w  w  w  .j  a va2s.  c  om
    try {
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("Authorization", IMGUR_CLIENT_ID);
        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        // Starts the query
        conn.connect();
        int response = conn.getResponseCode();
        if (response != SC_OK) {
            FLog.e(TAG, "Album request returned %s", response);
            return null;
        }
        is = conn.getInputStream();
        return readAsString(is);
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

From source file:Main.java

private static InputStream getInputStreamFromUrl_V9(Context paramContext, String paramString) {
    if (confirmDownload(paramContext, paramString)) {
        try {/*from  w  w  w.  ja v  a2 s  .c  o m*/

            URL localURL = new URL(paramString);
            HttpURLConnection localHttpURLConnection2 = (HttpURLConnection) localURL.openConnection();
            localHttpURLConnection2.setRequestProperty("Accept-Charset", "UTF-8");
            localHttpURLConnection2.setReadTimeout(30000);
            localHttpURLConnection2.setConnectTimeout(30000);
            localHttpURLConnection2.setRequestMethod("GET");
            localHttpURLConnection2.setDoInput(true);
            localHttpURLConnection2.connect();
            return localHttpURLConnection2.getInputStream();

        } catch (Throwable localThrowable) {

            localThrowable.printStackTrace();
            return null;

        }
    } else {
        return null;
    }
}

From source file:org.LinuxdistroCommunity.android.client.NetworkUtilities.java

public static String getAuthToken(String server, String code) {

    String token = null;//  w  ww  . j a  va2s .c  o  m

    final ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair(PARAM_CODE, code));
    params.add(new BasicNameValuePair(PARAM_CLIENT_SECRET, CLIENT_SECRET));

    InputStream is = null;
    URL auth_token_url;
    try {
        auth_token_url = getRequestURL(server, PATH_OAUTH_ACCESS_TOKEN, params);
        Log.i(TAG, auth_token_url.toString());

        HttpURLConnection conn = (HttpURLConnection) auth_token_url.openConnection();
        conn.setReadTimeout(10000 /* milliseconds */);
        conn.setConnectTimeout(15000 /* milliseconds */);
        conn.setRequestMethod("GET");
        conn.setDoInput(true);
        // Starts the query
        conn.connect();
        int response_code = conn.getResponseCode();
        Log.d(TAG, "The response is: " + response_code);
        is = conn.getInputStream();

        // parse token_response as JSON to get the token out
        String str_response = readStreamToString(is, 500);
        Log.d(TAG, str_response);
        JSONObject response = new JSONObject(str_response);
        token = response.getString("access_token");

    } catch (MalformedURLException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        // Makes sure that the InputStream is closed after the app is
        // finished using it.
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    Log.i(TAG, token);
    return token;
}

From source file:hackathon.openrice.CardsActivity.java

public static Bitmap getBitmapFromURL(String src) {
    try {/*w w w . j a  va 2  s.c o  m*/
        URL url = new URL(src);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        return myBitmap;
    } catch (IOException e) {
        //e.printStackTrace();
        return null;
    }
}

From source file:Main.java

public static void downloadImage(String imageUrl) {
    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
        Log.d("TAG", "monted sdcard");
    } else {/*w w  w  .  jav  a  2s  .  co  m*/
        Log.d("TAG", "has no sdcard");
    }
    HttpURLConnection con = null;
    FileOutputStream fos = null;
    BufferedOutputStream bos = null;
    BufferedInputStream bis = null;
    File imageFile = null;
    try {
        URL url = new URL(imageUrl);
        con = (HttpURLConnection) url.openConnection();
        con.setConnectTimeout(5 * 1000);
        con.setReadTimeout(15 * 1000);
        con.setDoInput(true);
        con.setDoOutput(true);
        bis = new BufferedInputStream(con.getInputStream());
        imageFile = new File(getImagePath(imageUrl));
        fos = new FileOutputStream(imageFile);
        bos = new BufferedOutputStream(fos);
        byte[] b = new byte[1024];
        int length;
        while ((length = bis.read(b)) != -1) {
            bos.write(b, 0, length);
            bos.flush();
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (bis != null) {
                bis.close();
            }
            if (bos != null) {
                bos.close();
            }
            if (con != null) {
                con.disconnect();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    if (imageFile != null) {
    }
}

From source file:com.samsung.msf.youtubeplayer.client.util.FeedParser.java

/**
 * Given a string representation of a URL, sets up a connection and gets an input stream.
 *///from  w  w w.ja  va  2s. co  m
public static InputStream downloadUrl(final URL url) throws IOException {
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setReadTimeout(NET_READ_TIMEOUT_MILLIS /* milliseconds */);
    conn.setConnectTimeout(NET_CONNECT_TIMEOUT_MILLIS /* milliseconds */);
    conn.setRequestMethod("GET");
    conn.setDoInput(true);
    // Starts the query
    conn.connect();
    return conn.getInputStream();
}

From source file:com.zf.util.Post_NetNew.java

public static String pn(Map<String, String> pams) throws Exception {
    if (null == pams) {
        return "";
    }//from w ww.j a va  2 s  .c o  m
    String strtmp = "url";
    URL url = new URL(pams.get(strtmp));
    pams.remove(strtmp);
    strtmp = "body";
    String body = pams.get(strtmp);
    pams.remove(strtmp);
    strtmp = "POST";
    if (StringUtils.isEmpty(body))
        strtmp = "GET";
    HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
    httpConn.setUseCaches(false);
    httpConn.setRequestMethod(strtmp);
    for (String pam : pams.keySet()) {
        httpConn.setRequestProperty(pam, pams.get(pam));
    }
    if ("POST".equals(strtmp)) {
        httpConn.setDoOutput(true);
        httpConn.setDoInput(true);
        DataOutputStream dos = new DataOutputStream(httpConn.getOutputStream());
        dos.writeBytes(body);
        dos.flush();
    }
    int resultCode = httpConn.getResponseCode();
    StringBuilder sb = new StringBuilder();
    sb.append(resultCode).append("\n");
    String readLine;
    InputStream stream;
    try {
        stream = httpConn.getInputStream();
    } catch (Exception ignored) {
        stream = httpConn.getErrorStream();
    }
    try {
        BufferedReader responseReader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
        while ((readLine = responseReader.readLine()) != null) {
            sb.append(readLine).append("\n");
        }
    } catch (Exception ignored) {
    }

    return sb.toString();
}

From source file:com.lostad.app.base.util.RequestUtil.java

/** 
 * HTTP??????,??? /*w w  w  .  j ava 2  s  .  co m*/
 * @param actionUrl  
 * @param params ? key???,value? 
 * @param files 
 * @throws Exception 
 */
public static String postFile(String actionUrl, Map<String, String> params, FormFile[] files, String token)
        throws Exception {
    try {
        String BOUNDARY = "---------7d4a6d158c9"; //?  
        String MULTIPART_FORM_DATA = "multipart/form-data";

        URL url = new URL(actionUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoInput(true);//?  
        conn.setDoOutput(true);//?  
        conn.setUseCaches(false);//?Cache  
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Charset", "UTF-8");
        conn.setRequestProperty("Content-Type", MULTIPART_FORM_DATA + "; boundary=" + BOUNDARY);
        conn.setRequestProperty("token", token);
        //????
        StringBuilder sb = new StringBuilder();
        if (params != null) {
            for (Map.Entry<String, String> entry : params.entrySet()) {//?  
                sb.append("--");
                sb.append(BOUNDARY);
                sb.append("\r\n");
                sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"\r\n\r\n");
                sb.append(entry.getValue());
                sb.append("\r\n");
            }
        }

        DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
        outStream.write(sb.toString().getBytes());//????  

        //??  
        for (FormFile file : files) {
            StringBuilder split = new StringBuilder();
            split.append("--");
            split.append(BOUNDARY);
            split.append("\r\n");
            split.append("Content-Disposition: form-data;name=\"" + file.getFormname() + "\";filename=\""
                    + file.getFilname() + "\"\r\n");
            split.append("Content-Type: " + file.getContentType() + "\r\n\r\n");
            outStream.write(split.toString().getBytes());
            outStream.write(file.getData(), 0, file.getData().length);
            outStream.write("\r\n".getBytes());
        }
        byte[] end_data = ("--" + BOUNDARY + "--\r\n").getBytes();//??           
        outStream.write(end_data);
        outStream.flush();
        int cah = conn.getResponseCode();
        if (cah != 200)
            throw new RuntimeException("url");
        InputStream is = conn.getInputStream();
        int ch;
        StringBuilder b = new StringBuilder();
        while ((ch = is.read()) != -1) {
            b.append((char) ch);
        }
        outStream.close();
        conn.disconnect();
        return b.toString();
    } catch (Exception e) {

        throw e;
    }
}

From source file:com.adr.raspberryleds.HTTPUtils.java

public static JSONObject execPOST(String address, JSONObject params) throws IOException {

    BufferedReader readerin = null;
    Writer writerout = null;/* w  ww . j a  v a  2 s.c om*/

    try {
        URL url = new URL(address);
        String query = params.toString();

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setReadTimeout(10000 /* milliseconds */);
        connection.setConnectTimeout(15000 /* milliseconds */);
        connection.setRequestMethod("POST");
        connection.setAllowUserInteraction(false);

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

        connection.addRequestProperty("Content-Type", "application/json,encoding=UTF-8");
        connection.addRequestProperty("Content-length", String.valueOf(query.length()));

        writerout = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
        writerout.write(query);
        writerout.flush();

        writerout.close();
        writerout = null;

        int responsecode = connection.getResponseCode();
        if (responsecode == HttpURLConnection.HTTP_OK) {
            StringBuilder text = new StringBuilder();

            readerin = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line = null;
            while ((line = readerin.readLine()) != null) {
                text.append(line);
                text.append(System.getProperty("line.separator"));
            }

            JSONObject result = new JSONObject(text.toString());

            if (result.has("exception")) {
                throw new IOException(
                        MessageFormat.format("Remote exception: {0}.", result.getString("exception")));
            } else {
                return result;
            }
        } else {
            throw new IOException(MessageFormat.format("HTTP response error: {0}. {1}",
                    Integer.toString(responsecode), connection.getResponseMessage()));
        }
    } catch (JSONException ex) {
        throw new IOException(MessageFormat.format("Parse exception: {0}.", ex.getMessage()));
    } finally {
        if (writerout != null) {
            writerout.close();
            writerout = null;
        }
        if (readerin != null) {
            readerin.close();
            readerin = null;
        }
    }
}

From source file:com.gson.util.HttpKit.java

/**
 * //  w ww. ja  v a  2  s  .co  m
 * @param url
 * @param params
 * @param file
 * @return
 * @throws IOException
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws KeyManagementException
 */
public static String upload(String url, File file)
        throws IOException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
    String BOUNDARY = "----WebKitFormBoundaryiDGnV9zdZA1eM1yL"; // ?  
    StringBuffer bufferRes = null;
    URL urlGet = new URL(url);
    HttpURLConnection conn = (HttpURLConnection) urlGet.openConnection();
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setUseCaches(false);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("connection", "Keep-Alive");
    conn.setRequestProperty("user-agent",
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1700.107 Safari/537.36");
    conn.setRequestProperty("Charsert", "UTF-8");
    conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

    OutputStream out = new DataOutputStream(conn.getOutputStream());
    byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();// ??  
    StringBuilder sb = new StringBuilder();
    sb.append("--");
    sb.append(BOUNDARY);
    sb.append("\r\n");
    sb.append("Content-Disposition: form-data;name=\"media\";filename=\"" + file.getName() + "\"\r\n");
    sb.append("Content-Type:application/octet-stream\r\n\r\n");
    byte[] data = sb.toString().getBytes();
    out.write(data);
    DataInputStream fs = new DataInputStream(new FileInputStream(file));
    int bytes = 0;
    byte[] bufferOut = new byte[1024];
    while ((bytes = fs.read(bufferOut)) != -1) {
        out.write(bufferOut, 0, bytes);
    }
    out.write("\r\n".getBytes()); //  
    fs.close();
    out.write(end_data);
    out.flush();
    out.close();

    // BufferedReader???URL?  
    InputStream in = conn.getInputStream();
    BufferedReader read = new BufferedReader(new InputStreamReader(in, DEFAULT_CHARSET));
    String valueString = null;
    bufferRes = new StringBuffer();
    while ((valueString = read.readLine()) != null) {
        bufferRes.append(valueString);
    }
    in.close();
    if (conn != null) {
        // 
        conn.disconnect();
    }
    return bufferRes.toString();
}