zoukankan      html  css  js  c++  java
  • 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);
     }

    }

  • 相关阅读:
    黑马程序员_java基础笔记(13)...类加载器和代理
    nyoj-411-Friends number
    nyoj-38-布线问题
    nyoj-233-Sort it
    nyoj-115-城市平乱
    nyoj-608-畅通工程
    nyoj-36-最长公共子序列
    nyoj-150-Train Problem I
    nyoj-494-Dancing With the Googlers
    nyoj-214-单调递增子序列(二)
  • 原文地址:https://www.cnblogs.com/lianghui66/p/2856101.html
Copyright © 2011-2022 走看看