一、安装jar包
下载地址为:点击打开链接
安装方法:解压后将releases目录中的最后一个jar包放到安装工程libs目录下即可。
二、Layout布局文件
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.hxzy.asynchttpclient.MainActivity" >
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:id="@+id/image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1" />
<TextView
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1" />
</LinearLayout>
</ScrollView>
</RelativeLayout>
三、Java代码
package com.hxzy.asynchttpclient;
import org.apache.http.Header;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpRequest;
import com.loopj.android.http.AsyncHttpResponseHandler;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
private final String URL1 = "http://www.baidu.com";
private final String URL2 = "http://a.hiphotos.baidu.com/image/pic/item/8d5494eef01f3a29dd2a44c09b25bc315d607cda.jpg";
TextView text;
ImageView image;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.text);
image = (ImageView) findViewById(R.id.image);
setImageView();
setTextView();
}
private void setTextView() {
AsyncHttpClient httpClient = new AsyncHttpClient();
httpClient.get(URL1, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
text.setText(new String(response));
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] response, Throwable error) {
Toast.makeText(getApplicationContext(), "失败", 0).show();
}
});
}
private void setImageView() {
AsyncHttpClient httpClient = new AsyncHttpClient();
httpClient.get(URL2, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
BitmapFactory factory = new BitmapFactory();
Bitmap bitmap = factory.decodeByteArray(response, 0, response.length);
image.setImageBitmap(bitmap);
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] response, Throwable error) {
Toast.makeText(getApplicationContext(), "失败", 0).show();
}
});
}
}
<uses-permission android:name="android.permission.INTERNET"/>