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.adanac.module.blog.api.HttpApiHelper.java

public static void baiduPush(int remain) {
    String pushUrl = DaoFactory.getDao(HtmlPageDao.class).findPushUrl();
    if (pushUrl == null) {
        if (logger.isInfoEnabled()) {
            logger.info("all html page has been pushed!");
        }/*from w  ww  .  jav a 2s . c  o m*/
        return;
    }
    if (remain <= 0) {
        if (logger.isInfoEnabled()) {
            logger.info("there has no remain[" + remain + "]!");
        }
        return;
    }
    if (logger.isInfoEnabled()) {
        logger.info("find push url : " + pushUrl);
    }
    String url = "http://data.zz.baidu.com/urls?site=" + site + "&token=" + token;
    try {
        HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "text/plain");
        OutputStream outputStream = connection.getOutputStream();
        outputStream.write(pushUrl.getBytes("UTF-8"));
        outputStream.write("\r\n".getBytes("UTF-8"));
        outputStream.flush();
        int status = connection.getResponseCode();
        if (logger.isInfoEnabled()) {
            logger.info("baidu-push response code : " + status);
        }
        if (status == HttpServletResponse.SC_OK) {
            String response = IOUtil.read(connection.getInputStream());
            if (logger.isInfoEnabled()) {
                logger.info("baidu-push response : " + response);
            }
            JSONObject result = JSONObject.fromObject(response);
            if (result.getInt("success") >= 1) {
                DaoFactory.getDao(HtmlPageDao.class).updateIsPush(pushUrl);
            } else {
                logger.warn("push url failed : " + pushUrl);
            }
            baiduPush(result.getInt("remain"));
        } else {
            logger.error("baidu-push error : " + IOUtil.read(connection.getErrorStream()));
        }
    } catch (Exception e) {
        logger.error("baidu push failed ...", e);
    }
}

From source file:com.mopaas_mobile.http.BaseHttpRequester.java

public static String doPOST(String urlstr, List<BasicNameValuePair> params) throws IOException {
    String result = null;/*from w  ww  .  j  a  va2 s.c  o m*/
    URL url = new URL(urlstr);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setDoOutput(true);
    connection.setDoInput(true);
    connection.setRequestMethod("POST");
    connection.setUseCaches(false);
    connection.setInstanceFollowRedirects(false);
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    //       connection.setRequestProperty("token",token);
    connection.setConnectTimeout(30000);
    connection.setReadTimeout(30000);
    connection.connect();

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

    String content = "";
    if (params != null && params.size() > 0) {
        for (int i = 0; i < params.size(); i++) {
            content = content + "&" + URLEncoder.encode(((NameValuePair) params.get(i)).getName(), "UTF-8")
                    + "=" + URLEncoder.encode(((NameValuePair) params.get(i)).getValue(), "UTF-8");
        }
        out.writeBytes(content.substring(1));
    }

    out.flush();
    out.close();
    InputStream is = connection.getInputStream();
    BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

    StringBuffer b = new StringBuffer();
    int ch;
    while ((ch = br.read()) != -1) {
        b.append((char) ch);
    }
    result = b.toString().trim();
    connection.disconnect();
    return result;
}

From source file:com.mopaas_mobile.http.BaseHttpRequester.java

public static String doGETwithHeader(String urlstr, String token, List<BasicNameValuePair> params)
        throws IOException {
    String result = null;//  www . j a  va2  s. c  o m
    String content = "";
    for (int i = 0; i < params.size(); i++) {
        content = content + "&" + URLEncoder.encode(((NameValuePair) params.get(i)).getName(), "UTF-8") + "="
                + URLEncoder.encode(((NameValuePair) params.get(i)).getValue(), "UTF-8");
    }
    URL url = new URL(urlstr + "?" + content.substring(1));
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestProperty("token", token);
    connection.setDoInput(true);
    connection.setRequestMethod("GET");
    connection.setUseCaches(false);
    connection.connect();
    InputStream is = connection.getInputStream();
    BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

    StringBuffer b = new StringBuffer();
    int ch;
    while ((ch = br.read()) != -1) {
        b.append((char) ch);
    }
    result = b.toString().trim();
    connection.disconnect();
    return result;
}

From source file:Main.java

public static String uploadFile(File file, String RequestURL) {
    String BOUNDARY = UUID.randomUUID().toString();
    String PREFIX = "--", LINE_END = "\r\n";
    String CONTENT_TYPE = "multipart/form-data";

    try {/*from www .ja v  a  2  s  .c  om*/
        URL url = new URL(RequestURL);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(TIME_OUT);
        conn.setConnectTimeout(TIME_OUT);
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Charset", CHARSET);
        conn.setRequestProperty("connection", "keep-alive");
        conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
        if (file != null) {

            OutputStream outputSteam = conn.getOutputStream();

            DataOutputStream dos = new DataOutputStream(outputSteam);
            StringBuffer sb = new StringBuffer();
            sb.append(PREFIX);
            sb.append(BOUNDARY);
            sb.append(LINE_END);

            sb.append("Content-Disposition: form-data; name=\"img\"; filename=\"" + file.getName() + "\""
                    + LINE_END);
            sb.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINE_END);
            sb.append(LINE_END);
            dos.write(sb.toString().getBytes());
            InputStream is = new FileInputStream(file);
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = is.read(bytes)) != -1) {
                dos.write(bytes, 0, len);
            }
            is.close();
            dos.write(LINE_END.getBytes());
            byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
            dos.write(end_data);
            dos.flush();

            int res = conn.getResponseCode();
            Log.e(TAG, "response code:" + res);
            if (res == 200) {
                return SUCCESS;
            }
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return FAILURE;
}

From source file:com.android.feedmeandroid.HTTPClient.java

public static Bitmap downloadFile(final String fileUrl) {
    final Bitmap[] bitmap = new Bitmap[1];
    Thread t = new Thread(new Runnable() {
        public void run() {
            URL myFileUrl = null;
            try {
                myFileUrl = new URL(fileUrl);
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();// w w  w. j  ava 2s  .  co  m
            }
            try {
                HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
                conn.setDoInput(true);
                conn.connect();
                InputStream is = conn.getInputStream();

                Bitmap bmImg = BitmapFactory.decodeStream(is);
                bitmap[0] = bmImg;
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    });
    t.start();
    try {
        t.join();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return bitmap[0];
}

From source file:Main.java

public static boolean isConnectionAvailable() {
    class NetworkCheckTask extends AsyncTask<Void, Void, Boolean> {

        @Override// w  w  w  . j a  v a  2 s.  c  o m
        protected Boolean doInBackground(Void... params) {
            try {
                URL url = new URL(MAD_SERVER + "/sync.html");
                HttpURLConnection conn = null;
                conn = (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(999);
                conn.setRequestMethod("GET");
                conn.setDoInput(true);
                conn.connect();
                if (conn.getResponseCode() == 200)
                    return true;
                else
                    return false;
            } catch (Exception e) {
                return false;
            }
        }

    }

    try {
        NetworkCheckTask async = new NetworkCheckTask();
        async.execute();
        return async.get();
    } catch (Exception e) {
        return false;
    }
}

From source file:chen.android.toolkit.network.HttpConnection.java

/**
 * </br><b>title : </b>      ????POST??
 * </br><b>description :</b>????POST??
 * </br><b>time :</b>      2012-7-8 ?4:34:08
 * @param method         ??//from   w w w.j ava  2 s . com
 * @param url            POSTURL
 * @param datas            ????
 * @return               ???
 * @throws IOException
 */
private static InputStream connect(String method, URL url, byte[]... datas) throws IOException {
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setDoOutput(true);
    conn.setDoInput(true);
    conn.setRequestMethod(method);
    conn.setUseCaches(false);
    conn.setInstanceFollowRedirects(true);
    conn.setConnectTimeout(6 * 1000);
    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    conn.setRequestProperty("Connection", "Keep-Alive");
    conn.setRequestProperty("Charset", "UTF-8");
    OutputStream outputStream = conn.getOutputStream();
    for (byte[] data : datas) {
        outputStream.write(data);
    }
    outputStream.close();
    return conn.getInputStream();
}

From source file:Main.java

public static String httpPost(String urlStr, List<NameValuePair> params) {

    String paramsEncoded = "";
    if (params != null) {
        paramsEncoded = URLEncodedUtils.format(params, "UTF-8");
    }/*from   w  w w . j a va2  s .  c o m*/

    String result = null;
    URL url = null;
    HttpURLConnection connection = null;
    InputStreamReader in = null;
    try {
        url = new URL(urlStr);
        connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("Charset", "utf-8");
        DataOutputStream dop = new DataOutputStream(connection.getOutputStream());
        dop.writeBytes(paramsEncoded);
        dop.flush();
        dop.close();

        in = new InputStreamReader(connection.getInputStream());
        BufferedReader bufferedReader = new BufferedReader(in);
        StringBuffer strBuffer = new StringBuffer();
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            strBuffer.append(line);
        }
        result = strBuffer.toString();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
    return result;
}

From source file:Main.java

/**
 * Issue a POST request to the server./*from   w  w  w  . j ava  2s.  c  o m*/
 *
 * @param endpoint POST address.
 * @param params request parameters.
 * @return response
 * @throws IOException propagated from POST.
 */
private static String executePost(String endpoint, Map<String, String> params) throws IOException {
    URL url;
    StringBuffer response = new StringBuffer();
    try {
        url = new URL(endpoint);
    } catch (MalformedURLException e) {
        throw new IllegalArgumentException("invalid url: " + endpoint);
    }
    StringBuilder bodyBuilder = new StringBuilder();
    Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
    // constructs the POST body using the parameters
    while (iterator.hasNext()) {
        Entry<String, String> param = iterator.next();
        bodyBuilder.append(param.getKey()).append('=').append(param.getValue());
        if (iterator.hasNext()) {
            bodyBuilder.append('&');
        }
    }
    String body = bodyBuilder.toString();
    //Log.v(TAG, "Posting '" + body + "' to " + url);
    byte[] bytes = body.getBytes();
    HttpURLConnection conn = null;
    try {
        conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setUseCaches(false);
        conn.setFixedLengthStreamingMode(bytes.length);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");

        // post the request
        OutputStream out = conn.getOutputStream();
        out.write(bytes);
        out.close();

        // handle the response
        int status = conn.getResponseCode();
        if (status != 200) {
            throw new IOException("Post failed with error code " + status);

        } else {
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
        }
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
    return response.toString();
}

From source file:Main.java

public static String UpdateScore(String userName, int br) {

    String retStr = "";

    try {/*from   ww  w.ja v  a 2  s.c om*/
        URL url = new URL("http://" + IP_ADDRESS + "/RiddleQuizApp/ServerSide/AzurirajHighScore.php");

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(15000);
        conn.setReadTimeout(10000);
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);
        Log.e("http", "por1");

        JSONObject data = new JSONObject();

        data.put("username", userName);
        data.put("broj", br);

        Log.e("http", "por3");

        Uri.Builder builder = new Uri.Builder().appendQueryParameter("action", data.toString());
        String query = builder.build().getEncodedQuery();

        Log.e("http", "por4");

        OutputStream os = conn.getOutputStream();
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        bw.write(query);
        Log.e("http", "por5");
        bw.flush();
        bw.close();
        os.close();
        int responseCode = conn.getResponseCode();

        Log.e("http", String.valueOf(responseCode));
        if (responseCode == HttpURLConnection.HTTP_OK) {
            retStr = inputStreamToString(conn.getInputStream());
        } else
            retStr = String.valueOf("Error: " + responseCode);

        Log.e("http", retStr);

    } catch (Exception e) {
        Log.e("http", "greska");
    }
    return retStr;
}