Example usage for java.io InputStreamReader read

List of usage examples for java.io InputStreamReader read

Introduction

In this page you can find the example usage for java.io InputStreamReader read.

Prototype

public int read(java.nio.CharBuffer target) throws IOException 

Source Link

Document

Attempts to read characters into the specified character buffer.

Usage

From source file:cn.com.zhenshiyin.crowd.net.AsyncHttpPost.java

@Override
public void run() {
    String ret = "";
    try {/*from ww w. ja v a  2  s.  co  m*/
        request = new HttpPost(url);
        if (Constants.isGzip) {
            request.addHeader("Accept-Encoding", "gzip");
        } else {
            request.addHeader("Accept-Encoding", "default");
        }
        LogUtil.d(AsyncHttpPost.class.getName(), "AsyncHttpPost  request to url :" + url);

        if (parameter != null && parameter.size() > 0) {
            List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
            for (RequestParameter p : parameter) {
                list.add(new BasicNameValuePair(p.getName(), p.getValue()));
            }
            ((HttpPost) request).setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8));
        }
        httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectTimeout);
        httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, readTimeout);
        HttpResponse response = httpClient.execute(request);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.SC_OK) {
            InputStream is = response.getEntity().getContent();
            BufferedInputStream bis = new BufferedInputStream(is);
            bis.mark(2);
            // ??
            byte[] header = new byte[2];
            int result = bis.read(header);
            // reset??
            bis.reset();
            // ?GZIP?
            int headerData = getShort(header);
            // Gzip ? ? 0x1f8b
            if (result != -1 && headerData == 0x1f8b) {
                LogUtil.d("HttpTask", " use GZIPInputStream  ");
                is = new GZIPInputStream(bis);
            } else {
                LogUtil.d("HttpTask", " not use GZIPInputStream");
                is = bis;
            }
            InputStreamReader reader = new InputStreamReader(is, "utf-8");
            char[] data = new char[100];
            int readSize;
            StringBuffer sb = new StringBuffer();
            while ((readSize = reader.read(data)) > 0) {
                sb.append(data, 0, readSize);
            }
            ret = sb.toString();
            bis.close();
            reader.close();

        } else {
            RequestException exception = new RequestException(RequestException.IO_EXCEPTION,
                    "??,??" + statusCode);
            ret = ErrorUtil.errorJson("ERROR.HTTP.001", exception.getMessage());
        }

        LogUtil.d(AsyncHttpPost.class.getName(), "AsyncHttpPost  request to url :" + url + "  finished !");
    } catch (java.lang.IllegalArgumentException e) {
        RequestException exception = new RequestException(RequestException.IO_EXCEPTION,
                Constants.ERROR_MESSAGE);
        ret = ErrorUtil.errorJson("ERROR.HTTP.002", exception.getMessage());
        LogUtil.d(AsyncHttpGet.class.getName(),
                "AsyncHttpPost  request to url :" + url + "  onFail  " + e.getMessage());
    } catch (org.apache.http.conn.ConnectTimeoutException e) {
        RequestException exception = new RequestException(RequestException.SOCKET_TIMEOUT_EXCEPTION,
                Constants.ERROR_MESSAGE);
        ret = ErrorUtil.errorJson("ERROR.HTTP.003", exception.getMessage());
        LogUtil.d(AsyncHttpPost.class.getName(),
                "AsyncHttpPost  request to url :" + url + "  onFail  " + e.getMessage());
    } catch (java.net.SocketTimeoutException e) {
        RequestException exception = new RequestException(RequestException.SOCKET_TIMEOUT_EXCEPTION,
                Constants.ERROR_MESSAGE);
        ret = ErrorUtil.errorJson("ERROR.HTTP.004", exception.getMessage());
        LogUtil.d(AsyncHttpPost.class.getName(),
                "AsyncHttpPost  request to url :" + url + "  onFail  " + e.getMessage());
    } catch (UnsupportedEncodingException e) {
        RequestException exception = new RequestException(RequestException.UNSUPPORTED_ENCODEING_EXCEPTION,
                "?");
        ret = ErrorUtil.errorJson("ERROR.HTTP.005", exception.getMessage());
        LogUtil.d(AsyncHttpPost.class.getName(),
                "AsyncHttpPost  request to url :" + url + "  UnsupportedEncodingException  " + e.getMessage());
    } catch (org.apache.http.conn.HttpHostConnectException e) {
        RequestException exception = new RequestException(RequestException.CONNECT_EXCEPTION, "");
        ret = ErrorUtil.errorJson("ERROR.HTTP.006", exception.getMessage());
        LogUtil.d(AsyncHttpPost.class.getName(),
                "AsyncHttpPost  request to url :" + url + "  HttpHostConnectException  " + e.getMessage());
    } catch (ClientProtocolException e) {
        RequestException exception = new RequestException(RequestException.CLIENT_PROTOL_EXCEPTION,
                "??");
        ret = ErrorUtil.errorJson("ERROR.HTTP.007", exception.getMessage());
        e.printStackTrace();
        LogUtil.d(AsyncHttpPost.class.getName(),
                "AsyncHttpPost  request to url :" + url + "  ClientProtocolException " + e.getMessage());
    } catch (IOException e) {
        RequestException exception = new RequestException(RequestException.IO_EXCEPTION, "??");
        ret = ErrorUtil.errorJson("ERROR.HTTP.008", exception.getMessage());
        e.printStackTrace();
        LogUtil.d(AsyncHttpPost.class.getName(),
                "AsyncHttpPost  request to url :" + url + "  IOException  " + e.getMessage());
    } finally {
        if (!Constants.IS_STOP_REQUEST) {
            Message msg = new Message();
            msg.obj = ret;
            LogUtil.d("", ret);
            msg.getData().putSerializable("callback", callBack);
            resultHandler.sendMessage(msg);
        }
        //
        if (customLoadingDialog != null && customLoadingDialog.isShowing()) {
            customLoadingDialog.dismiss();
            customLoadingDialog = null;
        }
    }
    super.run();
}

From source file:com.baofeng.game.sdk.net.AsyncHttpPost.java

@Override
public void run() {
    String ret = "";
    try {//from   w  w w. j a  va2s.co m
        for (int i = 0; i < BFGameConfig.CONNECTION_COUNT; i++) {
            try {
                request = new HttpPost(url);

                request.addHeader("Accept-Encoding", "default");

                if (parameter != null && parameter.size() > 0) {
                    List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();

                    for (RequestParameter p : parameter) {

                        list.add(new BasicNameValuePair(Util.encode(p.getName()), Util.encode(p.getValue())));
                        LogUtil.d("AsyncHttpPost Param ", p.getName() + " , " + p.getValue());

                    }
                    StringBuffer sb = new StringBuffer();
                    for (int j = 0; j < list.size(); j++) {
                        sb.append(list.get(j));
                        if (!(j == list.size() - 1)) {
                            sb.append("&");
                        }
                    }

                    BasicNameValuePair bn = new BasicNameValuePair("sign",
                            MD5Util.MD5(sb + "1234" + BFGameConfig.SERVERKEY));
                    //                  System.out.println("@@@" +  sb + "1234"
                    //                        + BFGameConfig.SERVERKEY);
                    list.add(bn);
                    ((HttpPost) request).setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8));

                }
                LogUtil.d("AsyncHttpPost : ", url);

                httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectTimeout);
                httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, readTimeout);
                HttpResponse response = httpClient.execute(request);
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode == HttpStatus.SC_OK) {
                    // HttpManager.saveCookies(response);
                    InputStream is = response.getEntity().getContent();
                    BufferedInputStream bis = new BufferedInputStream(is);
                    bis.mark(2);
                    // ??
                    byte[] header = new byte[2];
                    int result = bis.read(header);
                    // reset??
                    bis.reset();
                    // ?GZIP?
                    int headerData = getShort(header);
                    // Gzip ? ? 0x1f8b
                    if (result != -1 && headerData == 0x1f8b) {
                        is = new GZIPInputStream(bis);
                    } else {
                        is = bis;
                    }
                    InputStreamReader reader = new InputStreamReader(is, "utf-8");
                    char[] data = new char[100];
                    int readSize;
                    StringBuffer sb = new StringBuffer();
                    while ((readSize = reader.read(data)) > 0) {
                        sb.append(data, 0, readSize);
                    }
                    ret = sb.toString();
                    bis.close();
                    reader.close();

                } else {
                    RequestException exception = new RequestException(RequestException.IO_EXCEPTION,
                            "??,??" + statusCode);
                    ret = ErrorUtil.errorJson("-1", exception.getMessage());
                }

                break;
            } catch (Exception e) {
                if (i == BFGameConfig.CONNECTION_COUNT - 1) {
                    RequestException exception = new RequestException(RequestException.IO_EXCEPTION,
                            "");
                    ret = ErrorUtil.errorJson("-1", exception.getMessage());
                } else {
                    LogUtil.d("connection url", "" + i);
                    continue;
                }
            }
        }
    } catch (java.lang.IllegalArgumentException e) {
        RequestException exception = new RequestException(RequestException.IO_EXCEPTION,
                BFGameConfig.ERROR_MESSAGE);
        ret = ErrorUtil.errorJson("-2", exception.getMessage());
    } finally {
        if (!BFGameConfig.IS_STOP_REQUEST) {
            Message msg = new Message();
            msg.obj = ret;
            msg.getData().putSerializable("callback", callBack);
            resultHandler.sendMessage(msg);
        }
        if (customLoadingDialog != null && customLoadingDialog.isShowing()) {
            customLoadingDialog.dismiss();
            customLoadingDialog = null;
        }
    }
    super.run();
}

From source file:com.ibm.liberty.starter.service.swagger.api.v1.ProviderEndpoint.java

private String getOutput(Process joinProc) throws IOException {
    InputStream stream = joinProc.getInputStream();

    char[] buf = new char[512];
    int charsRead;
    StringBuilder sb = new StringBuilder();
    InputStreamReader reader = null;
    try {/*ww  w  . j a  v  a  2 s . c o  m*/
        reader = new InputStreamReader(stream);
        while ((charsRead = reader.read(buf)) > 0) {
            sb.append(buf, 0, charsRead);
        }
    } finally {
        if (reader != null) {
            reader.close();
        }
    }

    return sb.toString();
}

From source file:com.google.maps.android.utils.demo.HeatmapsPlacesDemoActivity.java

/**
 * Makes a radar search request and returns the results in a json format.
 *
 * @param keyword  The keyword to be searched for.
 * @param location The location the radar search should be based around.
 * @return The results from the radar search request as a json
 *///from   ww w  .  jav a  2 s . co  m
private String getJsonPlaces(String keyword, LatLng location) {
    HttpURLConnection conn = null;
    StringBuilder jsonResults = new StringBuilder();
    try {
        URL url = new URL(PLACES_API_BASE + TYPE_RADAR_SEARCH + OUT_JSON + "?location=" + location.latitude
                + "," + location.longitude + "&radius=" + (SEARCH_RADIUS / 2) + "&sensor=false" + "&key="
                + API_KEY + "&keyword=" + keyword.replace(" ", "%20"));
        conn = (HttpURLConnection) url.openConnection();
        InputStreamReader in = new InputStreamReader(conn.getInputStream());

        // Load the results into a StringBuilder
        int read;
        char[] buff = new char[1024];
        while ((read = in.read(buff)) != -1) {
            jsonResults.append(buff, 0, read);
        }
    } catch (MalformedURLException e) {
        Toast.makeText(this, "Error processing Places API URL", Toast.LENGTH_SHORT).show();
        return null;
    } catch (IOException e) {
        Toast.makeText(this, "Error connecting to Places API", Toast.LENGTH_SHORT).show();
        return null;
    } finally {
        if (conn != null) {
            conn.disconnect();
        }
    }
    return jsonResults.toString();
}

From source file:fi.hut.soberit.sensors.services.BatchDataUploadService.java

private String getRequestContent(final HttpResponse updateIdResponse) throws IOException {
    final StringBuilder builder = new StringBuilder();

    final InputStream content = updateIdResponse.getEntity() != null ? updateIdResponse.getEntity().getContent()
            : null;//from w w w  .j ava 2  s  .c  o  m

    if (content == null) {
        return null;
    }
    final InputStreamReader reader = new InputStreamReader(content);
    char[] buffer = new char[512];
    int res;
    do {
        res = reader.read(buffer);
        builder.append(buffer, 0, res);
    } while (res == 512);

    content.close();

    return builder.toString();
}

From source file:op.tools.SYSTools.java

/**
 * @param filePath name of file to open. The file can reside
 *                 anywhere in the classpath
 *                 http://snippets.dzone.com/posts/show/4480
 *//*  ww  w.  jav  a 2  s .c  o  m*/
public static String readFileAsString(String filePath) throws IOException {
    StringBuffer fileData = new StringBuffer(1000);
    FileInputStream fis = new FileInputStream(filePath);
    InputStreamReader reader = new InputStreamReader(fis, "UTF-8");
    char[] buf = new char[1024];
    int numRead = 0;
    while ((numRead = reader.read(buf)) != -1) {
        String readData = String.valueOf(buf, 0, numRead);
        fileData.append(readData);
        buf = new char[1024];
    }
    reader.close();
    fis.close();
    return fileData.toString();
}

From source file:com.pipi.studio.dev.net.AsyncHttpGet.java

@Override
public void run() {
    String ret = "";
    try {/*w  w w . j a  v  a  2 s.c o m*/
        if (parameter != null && parameter.size() > 0) {
            StringBuilder bulider = new StringBuilder();
            for (RequestParameter p : parameter) {
                if (bulider.length() != 0) {
                    bulider.append("&");
                }

                bulider.append(Utils.encode(p.getName()));
                bulider.append("=");
                bulider.append(Utils.encode(p.getValue()));
            }
            url += "?" + bulider.toString();
        }
        LogUtil.d(AsyncHttpGet.class.getName(), "AsyncHttpGet  request to url :" + url);
        request = new HttpGet(url);
        /*if(Constants.isGzip){
        request.addHeader("Accept-Encoding", "gzip");
          }else{
        request.addHeader("Accept-Encoding", "default");
          }*/
        //  
        httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectTimeout);
        // ? 
        httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, readTimeout);
        HttpResponse response = httpClient.execute(request);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.SC_OK) {
            InputStream is = response.getEntity().getContent();
            BufferedInputStream bis = new BufferedInputStream(is);
            bis.mark(2);
            // ??
            byte[] header = new byte[2];
            int result = bis.read(header);
            // reset??
            bis.reset();
            // ?GZIP?
            int headerData = getShort(header);
            // Gzip ? ? 0x1f8b
            if (result != -1 && headerData == 0x1f8b) {
                LogUtil.d("HttpTask", " use GZIPInputStream  ");
                is = new GZIPInputStream(bis);
            } else {
                LogUtil.d("HttpTask", " not use GZIPInputStream");
                is = bis;
            }
            InputStreamReader reader = new InputStreamReader(is, "utf-8");
            char[] data = new char[100];
            int readSize;
            StringBuffer sb = new StringBuffer();
            while ((readSize = reader.read(data)) > 0) {
                sb.append(data, 0, readSize);
            }
            ret = sb.toString();
            bis.close();
            reader.close();

            //            ByteArrayOutputStream content = new ByteArrayOutputStream();
            //            response.getEntity().writeTo(content);
            //            ret = new String(content.toByteArray()).trim();
            //            content.close();
        } else {
            RequestException exception = new RequestException(RequestException.IO_EXCEPTION,
                    "??,??" + statusCode);
            ret = ErrorUtil.errorJson("ERROR.HTTP.001", exception.getMessage());
        }

        LogUtil.d(AsyncHttpGet.class.getName(), "AsyncHttpGet  request to url :" + url + "  finished !");

    } catch (java.lang.IllegalArgumentException e) {

        RequestException exception = new RequestException(RequestException.IO_EXCEPTION,
                Constants.ERROR_MESSAGE);
        ret = ErrorUtil.errorJson("ERROR.HTTP.002", exception.getMessage());
        LogUtil.d(AsyncHttpGet.class.getName(),
                "AsyncHttpGet  request to url :" + url + "  onFail  " + e.getMessage());
    } catch (org.apache.http.conn.ConnectTimeoutException e) {
        RequestException exception = new RequestException(RequestException.SOCKET_TIMEOUT_EXCEPTION,
                Constants.ERROR_MESSAGE);
        ret = ErrorUtil.errorJson("ERROR.HTTP.003", exception.getMessage());
        LogUtil.d(AsyncHttpGet.class.getName(),
                "AsyncHttpGet  request to url :" + url + "  onFail  " + e.getMessage());
    } catch (java.net.SocketTimeoutException e) {
        RequestException exception = new RequestException(RequestException.SOCKET_TIMEOUT_EXCEPTION,
                Constants.ERROR_MESSAGE);
        ret = ErrorUtil.errorJson("ERROR.HTTP.004", exception.getMessage());
        LogUtil.d(AsyncHttpGet.class.getName(),
                "AsyncHttpGet  request to url :" + url + "  onFail  " + e.getMessage());
    } catch (UnsupportedEncodingException e) {
        RequestException exception = new RequestException(RequestException.UNSUPPORTED_ENCODEING_EXCEPTION,
                "?");
        ret = ErrorUtil.errorJson("ERROR.HTTP.005", exception.getMessage());
        LogUtil.d(AsyncHttpGet.class.getName(),
                "AsyncHttpGet  request to url :" + url + "  UnsupportedEncodingException  " + e.getMessage());
    } catch (org.apache.http.conn.HttpHostConnectException e) {
        RequestException exception = new RequestException(RequestException.CONNECT_EXCEPTION,
                Constants.ERROR_MESSAGE);
        ret = ErrorUtil.errorJson("ERROR.HTTP.006", exception.getMessage());
        LogUtil.d(AsyncHttpGet.class.getName(),
                "AsyncHttpGet  request to url :" + url + "  HttpHostConnectException  " + e.getMessage());
    } catch (ClientProtocolException e) {
        RequestException exception = new RequestException(RequestException.CLIENT_PROTOL_EXCEPTION,
                "??");
        ret = ErrorUtil.errorJson("ERROR.HTTP.007", exception.getMessage());
        e.printStackTrace();
        LogUtil.d(AsyncHttpGet.class.getName(),
                "AsyncHttpGet  request to url :" + url + "  ClientProtocolException " + e.getMessage());
    } catch (IOException e) {
        RequestException exception = new RequestException(RequestException.IO_EXCEPTION, "??");
        ret = ErrorUtil.errorJson("ERROR.HTTP.008", exception.getMessage());
        e.printStackTrace();
        LogUtil.d(AsyncHttpGet.class.getName(),
                "AsyncHttpGet  request to url :" + url + "  IOException  " + e.getMessage());
    } finally {
        if (!Constants.IS_STOP_REQUEST) {
            Message msg = new Message();
            msg.obj = ret;
            LogUtil.d("result", ret);
            msg.getData().putSerializable("callback", callBack);
            resultHandler.sendMessage(msg);
        }
        //request.//
        if (customLoadingDialog != null && customLoadingDialog.isShowing()) {
            customLoadingDialog.dismiss();
            customLoadingDialog = null;
        }
    }
    super.run();
}

From source file:org.apache.chemistry.opencmis.server.impl.browser.POSTHttpServletRequestWrapper.java

public POSTHttpServletRequestWrapper(HttpServletRequest request, File tempDir, int memoryThreshold)
        throws Exception {
    super(request);

    parameters = new HashMap<String, String[]>();

    // parse query string
    parseFormData(request.getQueryString());

    // check multipart
    isMultipart = ServletFileUpload.isMultipartContent(request);

    if (isMultipart) {
        ServletFileUpload upload = new ServletFileUpload();
        FileItemIterator iter = upload.getItemIterator(request);

        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            String name = item.getFieldName();
            InputStream itemStream = new BufferedInputStream(item.openStream());

            if (item.isFormField()) {
                InputStreamReader reader = new InputStreamReader(itemStream, "UTF-8");

                try {
                    StringBuilder sb = new StringBuilder();

                    char[] buffer = new char[64 * 1024];
                    int b = 0;

                    while ((b = reader.read(buffer)) > -1) {
                        sb.append(buffer, 0, b);
                    }// w  w  w  .  ja va  2  s  . c om

                    addParameter(name, sb.toString());
                } finally {
                    try {
                        reader.close();
                    } catch (Exception e) {
                        // ignore
                    }
                }
            } else {
                filename = item.getName();
                contentType = ((item.getContentType() == null) ? Constants.MEDIATYPE_OCTETSTREAM
                        : item.getContentType());

                ThresholdOutputStream os = new ThresholdOutputStream(tempDir, memoryThreshold);

                try {
                    byte[] buffer = new byte[64 * 1024];
                    int b = 0;

                    while ((b = itemStream.read(buffer)) > -1) {
                        os.write(buffer, 0, b);
                    }

                    os.close();

                    size = BigInteger.valueOf(os.getSize());
                    stream = os.getInputStream();
                } catch (Exception e) {
                    // if something went wrong, make sure the temp file will
                    // be deleted
                    os.destroy();
                    throw e;
                } finally {
                    try {
                        itemStream.close();
                    } catch (Exception e) {
                        // ignore
                    }
                }
            }
        }

        String filenameControl = HttpUtils.getStringParameter(this, Constants.CONTROL_FILENAME);

        if (((filenameControl) != null) && (filenameControl.trim().length() > 0)) {
            filename = filenameControl;
        }

        String contentTypeControl = HttpUtils.getStringParameter(this, Constants.CONTROL_CONTENT_TYPE);

        if ((contentTypeControl != null) && (contentTypeControl.trim().length() > 0)) {
            contentType = contentTypeControl;
        }
    } else {
        // form data processing
        StringBuilder sb = new StringBuilder();

        InputStreamReader sr = new InputStreamReader(request.getInputStream(), "UTF-8");
        char[] buffer = new char[4096];
        int c = 0;

        while ((c = sr.read(buffer)) > -1) {
            sb.append(buffer, 0, c);
        }

        parseFormData(sb.toString());
    }
}

From source file:com.freedomotic.plugins.devices.ipx800.Ipx800.java

private void sendToBoard(Board board, Command c) throws IOException {
    try {// ww w  . ja  v a  2s .c  o m
        URL url = null;
        URLConnection urlConnection;
        String delimiter = configuration.getProperty("address-delimiter");
        String[] address = c.getProperty("address").split(delimiter);
        Integer relayNumber = Integer.parseInt(address[1]) - 1;

        if (c.getProperty("command").equals("CHANGE-STATE-DIGITAL-INPUT")) {
            relayNumber = relayNumber + 100;
        }
        // if required set the authentication
        if (board.getAuthentication().equalsIgnoreCase("true")) {
            String authString = board.getUsername() + ":" + board.getPassword();
            byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
            String authStringEnc = new String(authEncBytes);
            //Create a URL for the desired  page   
            url = new URL(
                    "http://" + board.getIpAddress() + ":" + board.getPort() + board.getPathAuthentication()
                            + "/" + CHANGE_STATE_RELAY_URL + relayNumber + "=" + c.getProperty("state-value"));
            urlConnection = url.openConnection();
            urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);
        } else {
            //Create a URL for the desired  page   
            url = new URL("http://" + board.getIpAddress() + ":" + board.getPort() + "/"
                    + CHANGE_STATE_RELAY_URL + relayNumber + "=" + c.getProperty("state-value"));
            urlConnection = url.openConnection();
        }
        LOG.info("Freedomotic sends the command " + url);
        InputStream is = urlConnection.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        int numCharsRead;
        char[] charArray = new char[1024];
        StringBuffer sb = new StringBuffer();
        while ((numCharsRead = isr.read(charArray)) > 0) {
            sb.append(charArray, 0, numCharsRead);
        }
        String result = sb.toString();
    } catch (MalformedURLException e) {
        LOG.error("Command malformed URL " + e.toString());
    } catch (IOException e) {
        LOG.error("Command IOexception" + e.toString());
    }
}

From source file:com.pursuer.reader.easyrss.WebpageItemViewCtrl.java

@SuppressLint("SimpleDateFormat")
private void showMobilizedPage() {
    showMobilized = true;// ww w .  j  av a2 s . c  om
    view.findViewById(R.id.Mobilized).setVisibility(View.VISIBLE);
    view.findViewById(R.id.OriginalContent).setVisibility(View.GONE);
    view.findViewById(R.id.BtnMobilzedPage).setEnabled(false);
    view.findViewById(R.id.BtnOriginalPage).setEnabled(true);
    view.findViewById(R.id.OriginalProgress).setVisibility(View.GONE);
    view.findViewById(R.id.MobilizedProgress).setVisibility(View.VISIBLE);
    view.findViewById(R.id.MobilizedContent).setVisibility(View.GONE);
    final TextView title = (TextView) view.findViewById(R.id.ItemTitle);
    title.setTextSize(TypedValue.COMPLEX_UNIT_DIP, fontSize * 4 / 3);
    title.setText(item.getTitle());
    final TextView info = (TextView) view.findViewById(R.id.ItemInfo);
    info.setTextSize(TypedValue.COMPLEX_UNIT_DIP, fontSize * 4 / 5);
    final StringBuilder infoText = new StringBuilder();
    final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    sdf.setTimeZone(TimeZone.getDefault());
    infoText.append(sdf.format(Utils.timestampToDate(item.getTimestamp())));
    if (item.getAuthor() != null && item.getAuthor().length() > 0) {
        infoText.append(" | By ");
        infoText.append(item.getAuthor());
    }
    if (item.getSourceTitle() != null && item.getSourceTitle().length() > 0) {
        infoText.append(" (");
        infoText.append(item.getSourceTitle());
        infoText.append(")");
    }
    info.setText(infoText);
    if (thread == null) {
        thread = new Thread(new Runnable() {
            @SuppressWarnings("deprecation")
            @Override
            public void run() {
                try {
                    final StringBuilder urlBuilder = new StringBuilder();
                    urlBuilder.append("http://easyrss.pursuer.me/parser?url=");
                    urlBuilder.append(URLEncoder.encode(item.getHref()));
                    urlBuilder.append("&email=");
                    urlBuilder.append(URLEncoder.encode(dataMgr.getSettingByName(Setting.SETTING_USERNAME)));
                    urlBuilder.append("&version=");
                    urlBuilder.append(context.getString(R.string.Version));
                    final URLConnection connection = new URL(urlBuilder.toString()).openConnection();
                    connection.setConnectTimeout(30 * 1000);
                    connection.setReadTimeout(20 * 1000);
                    final InputStreamReader input = new InputStreamReader(connection.getInputStream());
                    final StringBuilder builder = new StringBuilder();
                    final char buff[] = new char[8192];
                    int len;
                    while ((len = input.read(buff)) != -1) {
                        builder.append(new String(buff, 0, len));
                    }
                    builder.append(theme == SettingTheme.THEME_NORMAL ? DataUtils.DEFAULT_NORMAL_CSS
                            : DataUtils.DEFAULT_DARK_CSS);
                    pageContent = builder.toString();
                    handler.sendMessage(handler.obtainMessage(MSG_LOADING_FINISHED, WebpageItemViewCtrl.this));
                } catch (final MalformedURLException exception) {
                    exception.printStackTrace();
                    pageContent = genFailedToLoadContentPage(context, theme);
                    handler.sendMessage(handler.obtainMessage(MSG_LOADING_FINISHED, WebpageItemViewCtrl.this));
                } catch (final IOException exception) {
                    exception.printStackTrace();
                    pageContent = genFailedToLoadContentPage(context, theme);
                    handler.sendMessage(handler.obtainMessage(MSG_LOADING_FINISHED, WebpageItemViewCtrl.this));
                }
            }
        });
        thread.setPriority(Thread.MIN_PRIORITY);
        thread.start();
    } else if (!thread.isAlive()) {
        handler.sendMessage(handler.obtainMessage(MSG_LOADING_FINISHED, WebpageItemViewCtrl.this));
    }
}