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);
     }

    }

  • 相关阅读:
    poj3635(最短路)
    poj 3041( 最大匹配)
    poj 3522(生成树)
    poj 1904(强连通分量)
    poj 2446(二分匹配)
    poj 2400(最小权匹配)
    poj 2175(费用流消圈)
    poj 1256(搜索)
    poj 2195(最小费用流)
    poj 3613(最短路)
  • 原文地址:https://www.cnblogs.com/lianghui66/p/2856101.html
Copyright © 2011-2022 走看看