Example usage for java.net HttpURLConnection getInputStream

List of usage examples for java.net HttpURLConnection getInputStream

Introduction

In this page you can find the example usage for java.net HttpURLConnection getInputStream.

Prototype

public InputStream getInputStream() throws IOException 

Source Link

Document

Returns an input stream that reads from this open connection.

Usage

From source file:Main.java

public static byte[] executePost(String url, byte[] data, Map<String, String> requestProperties)
        throws IOException {
    HttpURLConnection urlConnection = null;
    try {//  w w w  .j a va 2s.  com
        urlConnection = (HttpURLConnection) new URL(url).openConnection();
        urlConnection.setRequestMethod("POST");
        urlConnection.setDoOutput(data != null);
        urlConnection.setDoInput(true);
        if (requestProperties != null) {
            for (Map.Entry<String, String> requestProperty : requestProperties.entrySet()) {
                urlConnection.setRequestProperty(requestProperty.getKey(), requestProperty.getValue());
            }
        }
        if (data != null) {
            OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
            out.write(data);
            out.close();
        }
        InputStream in = new BufferedInputStream(urlConnection.getInputStream());
        return convertInputStreamToByteArray(in);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
}

From source file:Main.java

public static String uploadFile(String filePath, String requestURL) {

    String result = "";
    File file = new File(filePath);

    try {/*from   w  ww  .j  a va2 s . c  o  m*/
        HttpURLConnection connection = initHttpURLConn(requestURL);

        if (filePath != null) {
            DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
            StringBuffer sb = new StringBuffer();
            InputStream is = new FileInputStream(filePath);
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = is.read(bytes)) != -1) {
                dos.write(bytes, 0, len);
            }
            dos.flush();
            is.close();
            int res = connection.getResponseCode();
            Log.e(TAG, "response code:" + res);
            if (res == 200) {
                Log.e(TAG, "request success");
                InputStream input = connection.getInputStream();
                StringBuffer sb1 = new StringBuffer();
                int ss;
                while ((ss = input.read()) != -1) {
                    sb1.append((char) ss);
                }

                result = sb1.toString();
                Log.d(TAG, "result: " + result);

                input.close();
            }
        }

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return result;

}

From source file:Main.java

public static String executePost(String targetURL, String urlParameters) {
    try {/*from  www .  j  a  v a2s .c  o m*/
        HttpURLConnection connection = (HttpURLConnection) new URL(targetURL).openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        //connection.setRequestProperty("Accept-Charset", charset);
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        OutputStream output = null;
        try {
            output = connection.getOutputStream();
            output.write(urlParameters.getBytes());
        } finally {
            if (output != null)
                try {
                    output.flush();
                    output.close();
                } catch (IOException logOrIgnore) {
                }
        }
        InputStream response = connection.getInputStream();
        String contentType = connection.getHeaderField("Content-Type");
        String responseStr = "";
        if (true) {
            BufferedReader reader = null;
            try {
                reader = new BufferedReader(new InputStreamReader(response));
                for (String line; (line = reader.readLine()) != null;) {
                    //System.out.println(line);
                    responseStr = responseStr + line;
                    Thread.sleep(2);
                }
            } finally {
                if (reader != null)
                    try {
                        reader.close();
                    } catch (IOException logOrIgnore) {
                    }
            }
        } else {
            // It's likely binary content, use InputStream/OutputStream.
            System.out.println("Binary content");
        }
        return responseStr;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return "";
}

From source file:yodlee.ysl.api.io.HTTP.java

public static String doGet(String url, Map<String, String> sessionTokens)
        throws IOException, URISyntaxException {
    String mn = "doIO(GET :" + url + ", sessionTokens =  " + sessionTokens.toString() + " )";
    System.out.println(fqcn + " :: " + mn);
    URL myURL = new URL(url);
    System.out.println(fqcn + " :: " + mn + ": Request URL=" + url.toString());
    HttpURLConnection conn = (HttpURLConnection) myURL.openConnection();
    //conn.setRequestMethod("GET");
    conn.setRequestProperty("User-Agent", userAgent);
    //conn.setRequestProperty("Content-Type", contentTypeJSON);
    //conn.setRequestProperty("Accept",);
    conn.setRequestProperty("Authorization", sessionTokens.toString());
    conn.setDoOutput(true);/*from  www  . j ava2s .  c o m*/
    System.out.println(fqcn + " :: " + mn + " : " + "Sending 'HTTP GET' request");
    int responseCode = conn.getResponseCode();
    System.out.println(fqcn + " :: " + mn + " : " + "Response Code : " + responseCode);
    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String inputLine;
    StringBuilder jsonResponse = new StringBuilder();
    while ((inputLine = in.readLine()) != null) {
        System.out.println(inputLine);
        jsonResponse.append(inputLine);
    }
    in.close();
    System.out.println(fqcn + " :: " + mn + " : " + jsonResponse.toString());
    return new String(jsonResponse);
}

From source file:com.nit.vicky.web.HttpFetcher.java

public static String downloadFileToSdCardMethod(String UrlToFile, Context context, String prefix, String method,
        Boolean isMP3) {/* ww  w  . j a  va2s  .  com*/
    try {
        URL url = new URL(UrlToFile);

        String extension = ".mp3";

        if (!isMP3)
            extension = UrlToFile.substring(UrlToFile.lastIndexOf("."));

        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setConnectTimeout(10 * 1000);
        urlConnection.setReadTimeout(10 * 1000);
        urlConnection.setRequestMethod(method);
        //urlConnection.setRequestProperty("Referer", "http://mm.taobao.com/");
        urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 ( compatible ) ");
        urlConnection.setRequestProperty("Accept", "*/*");
        urlConnection.connect();

        File file = File.createTempFile(prefix, extension, DiskUtil.getStoringDirectory());

        FileOutputStream fileOutput = new FileOutputStream(file);
        InputStream inputStream = urlConnection.getInputStream();

        byte[] buffer = new byte[1024];
        int bufferLength = 0;

        while ((bufferLength = inputStream.read(buffer)) > 0) {
            fileOutput.write(buffer, 0, bufferLength);
        }
        fileOutput.close();

        return file.getAbsolutePath();

    } catch (Exception e) {
        return "FAILED " + e.getMessage();
    }
}

From source file:gov.nasa.arc.geocam.geocam.HttpPost.java

public static int post(String url, Map<String, String> vars, String fileKey, String fileName,
        InputStream istream, String username, String password) throws IOException {
    HttpURLConnection conn = createConnection(url, username, password);

    try {/*from   w w  w  .  j a v  a2  s .  co  m*/
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

        Log.d("HttpPost", vars.toString());

        DataOutputStream out = new DataOutputStream(conn.getOutputStream());
        assembleMultipart(out, vars, fileKey, fileName, istream);
        istream.close();
        out.flush();

        InputStream in = conn.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in), 2048);

        // Set postedSuccess to true if there is a line in the HTTP response in
        // the form "GEOCAM_SHARE_POSTED <file>" where <file> equals fileName.
        // Our old success condition was just checking for HTTP return code 200; turns
        // out that sometimes gives false positives.
        Boolean postedSuccess = false;
        for (String line = reader.readLine(); line != null; line = reader.readLine()) {
            //Log.d("HttpPost", line);
            if (!postedSuccess && line.contains("GEOCAM_SHARE_POSTED")) {
                String[] vals = line.trim().split("\\s+");
                for (int i = 0; i < vals.length; ++i) {
                    //String filePosted = vals[1];
                    if (vals[i].equals(fileName)) {
                        Log.d(GeoCamMobile.DEBUG_ID, line);
                        postedSuccess = true;
                        break;
                    }
                }
            }
        }
        out.close();

        int responseCode = 0;
        responseCode = conn.getResponseCode();
        if (responseCode == 200 && !postedSuccess) {
            // our code for when we got value 200 but no confirmation
            responseCode = -3;
        }
        return responseCode;
    } catch (UnsupportedEncodingException e) {
        throw new IOException("HttpPost - Encoding exception: " + e);
    }

    // ??? when would this ever be thrown?
    catch (IllegalStateException e) {
        throw new IOException("HttpPost - IllegalState: " + e);
    }

    catch (IOException e) {
        try {
            return conn.getResponseCode();
        } catch (IOException f) {
            throw new IOException("HttpPost - IOException: " + e);
        }
    }
}

From source file:Main.java

/**
 * Do an HTTP POST and return the data as a byte array.
 *///from  w ww. j av a  2s.  c o m
public static byte[] executePost(String url, byte[] data, Map<String, String> requestProperties)
        throws MalformedURLException, IOException {
    HttpURLConnection urlConnection = null;
    try {
        urlConnection = (HttpURLConnection) new URL(url).openConnection();
        urlConnection.setRequestMethod("POST");
        urlConnection.setDoOutput(data != null);
        urlConnection.setDoInput(true);
        if (requestProperties != null) {
            for (Map.Entry<String, String> requestProperty : requestProperties.entrySet()) {
                urlConnection.setRequestProperty(requestProperty.getKey(), requestProperty.getValue());
            }
        }
        if (data != null) {
            OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
            out.write(data);
            out.close();
        }
        InputStream in = new BufferedInputStream(urlConnection.getInputStream());
        return convertInputStreamToByteArray(in);
    } finally {
        if (urlConnection != null) {
            urlConnection.disconnect();
        }
    }
}

From source file:com.thyn.backend.gcm.GcmSender.java

public static void sendMessageToTopic(String topic, String message) {
    try {//from   w w w  .ja  v a2 s  . com
        // Prepare JSON containing the GCM message content. What to send and where to send.
        JSONObject jGcmData = new JSONObject();
        JSONObject jData = new JSONObject();
        jData.put("message", message);
        // Where to send GCM message.
        String topicName = "/topics/topic_thyN_" + topic.trim();
        if (topic != null) {
            jGcmData.put("to", topicName);
        } else {
            jGcmData.put("to", "/topics/global");
        }
        // What to send in GCM message.
        jGcmData.put("data", jData);

        // Create connection to send GCM Message request.
        URL url = new URL("https://android.googleapis.com/gcm/send");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("Authorization", "key=" + API_KEY);
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);

        // Send GCM message content.
        OutputStream outputStream = conn.getOutputStream();
        outputStream.write(jGcmData.toString().getBytes());

        // Read GCM response.
        InputStream inputStream = conn.getInputStream();
        String resp = IOUtils.toString(inputStream);
        System.out.println(resp);
        System.out.println("Sending message: '" + message + "' to " + topicName);
        System.out.println("Check your device/emulator for notification or logcat for "
                + "confirmation of the receipt of the GCM message.");
    } catch (NullPointerException e) {
        e.printStackTrace();
    } catch (IOException e) {
        System.out.println("Unable to send GCM message.");
        System.out.println("Please ensure that API_KEY has been replaced by the server "
                + "API key, and that the device's registration token is correct (if specified).");
        e.printStackTrace();
    }
}

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 w  w.  ja  v a2 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:net.maxgigapop.mrs.driver.openstack.OpenStackRESTClient.java

private static String sendPOST(URL url, HttpURLConnection con, String body) throws IOException {

    con.setRequestMethod("POST");
    con.setRequestProperty("Content-type", "application/json");
    con.setRequestProperty("Accept", "application/json");

    con.setDoOutput(true);// w  w w .  j a v a2 s  . com
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(body);
    wr.flush();
    wr.close();

    logger.log(Level.INFO, "Sending POST request to URL : {0}", url);
    int responseCode = con.getResponseCode();
    logger.log(Level.INFO, "Response Code : {0}", responseCode);

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuilder responseStr = new StringBuilder();

    while ((inputLine = in.readLine()) != null) {
        responseStr.append(inputLine);
    }
    in.close();

    return responseStr.toString();

}