<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" > <Button android:text="使用httpClient请求数据" android:onClick="getpic" android:layout_width="match_parent" android:layout_height="wrap_content" /> <ImageView android:id="@+id/image_view" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout>package com.example.httpclient_02; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.ImageView; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import java.io.IOException; import java.io.InputStream; public class MainActivity extends AppCompatActivity { private ImageView imageView; private Handler handler=new Handler(){ @Override public void handleMessage(Message msg) { if (msg.what==0){ Bitmap bitmap=(Bitmap)msg.obj; imageView.setImageBitmap(bitmap); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); imageView = (ImageView) findViewById(R.id.image_view); } public void getpic(View view){ new Thread(){ @Override public void run() { try { //获取一个httpclient对象 HttpClient client=new DefaultHttpClient(); //找路径 String path = "http://03.imgmini.eastday.com/mobile/20170105/20170105110355_806f4ed3fe71d04fa452783d6736a02b_1_mwpm_03200403.jpeg"; //设置请求方式的对象 HttpGet httpGet=new HttpGet(path); //3.执行....返回值是http响应对象 HttpResponse httpResponse=client.execute(httpGet); //4.获取响应的状态码...先获取到响应的状态行,,,在获取响应的状态码 int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode==200){ InputStream inputStream = httpResponse.getEntity().getContent(); Bitmap bitmap = BitmapFactory.decodeStream(inputStream); Message message= Message.obtain(); message.what=0; message.obj=bitmap; handler.sendMessage(message); } } catch (IOException e) { e.printStackTrace(); } } }.start(); } }
Httpcilent请求数据
最新推荐文章于 2024-01-14 12:47:40 发布