• Httpclient访问网络


    public class MyAsyncTask extends AsyncTask<String, Integer, String> {

     private TextView textView;

     public MyAsyncTask(TextView textView) {
      this.textView = textView;
     }

     @Override
     protected String doInBackground(String... params) {
      String url = params[0];
      HttpClient client = new DefaultHttpClient();
    //  HttpPost httpPost = new HttpPost(url);
      HttpGet httpGet = new HttpGet(url);
      InputStream inputStream = null;
      long length = 0;
      try {
       HttpResponse response = client.execute(httpGet);
       HttpEntity entity = response.getEntity();
       inputStream = entity.getContent();
       length = entity.getContentLength();
      } catch (Exception e) {
       e.printStackTrace();
      }
      byte[] b = null;
      try {
       b = readStream(inputStream, length);
       inputStream.close();
      } catch (IOException e1) {
       e1.printStackTrace();
      }
      String string = "null";
      try {
       string = new String(b, "gb2312");
      } catch (UnsupportedEncodingException e) {
       e.printStackTrace();
      }
      //关闭Httpclient
      client.getConnectionManager().shutdown();
      return string;
     }

     public  byte[] readStream(InputStream inputStream, long length) throws IOException {

      byte[] b = new byte[1024];
      int ch = -1;
      //输出流是write,输入流是read
      //流程是先把inputStream读入字节数组b中,然后write进ByteArrayOutputStream,最后通过toByteArray()方法转化成自己数组
      ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
      int count = 0 ;
      while ((ch = inputStream.read(b)) != -1) {
       outputStream.write(b, 0, ch);
       count += ch;
       publishProgress((int)((count / length) * 100));
      }
      return outputStream.toByteArray();
     }

     @Override
     protected void onProgressUpdate(Integer... values) {
      super.onProgressUpdate(values);
      Log.e("process", values[0] + "");
     }

     @Override
     protected void onPostExecute(String result) {
      super.onPostExecute(result);
      textView.setText(result);
     }

    }

  • 相关阅读:
    Spark RDD简介与运行机制概述
    MongoDB 3.0.6的主,从,仲裁节点搭建
    kafka入门:简介、使用场景、设计原理、主要配置及集群搭建(转)
    Spark配置参数调优
    SparkSQL项目中的应用
    SparkSQL相关语句总结
    Hadoop系统架构
    Hadoop常用命令
    spark单机模式简单搭建
    Spark参数配置说明
  • 原文地址:https://www.cnblogs.com/lianghui66/p/2856101.html
Copyright © 2020-2023  润新知