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

}

原文地址:https://www.cnblogs.com/lianghui66/p/2856101.html