package com.example.asynchttpclient;
import org.apache.http.Header;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ImageView image = (ImageView) findViewById(R.id.image);
final TextView text=(TextView) findViewById(R.id.text);
AsyncHttpClient httpclient = new AsyncHttpClient();
String url = "http://pic16.nipic.com/20110908/6910138_102825181129_2.jpg";
httpclient.get(url,new AsyncHttpResponseHandler(){
@Override
public void onFailure(int arg0, Header[] arg1, byte[] arg2,
Throwable arg3) {
Toast.makeText(getApplicationContext(), "失败!", Toast.LENGTH_SHORT).show();
}
@Override
public void onSuccess(int statusCode, Header[] headers,byte[] response) {
BitmapFactory bf = new BitmapFactory();
Bitmap bitmap = bf.decodeByteArray(response, 0,response.length);
image.setImageBitmap(bitmap);
}
} );
String uri="http://www.baidu.com";
httpclient.get(uri, new AsyncHttpResponseHandler(){
@Override
public void onFailure(int arg0, Header[] arg1, byte[] arg2,
Throwable arg3) {
Toast.makeText(getApplicationContext(), "失败~!", Toast.LENGTH_SHORT).show();
}
@Override
public void onSuccess(int statusCode, Header[] headers,
byte[] response) {
text.setText(new String(response));
}});
}
}
<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.example.asynchttpclient.MainActivity" >
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
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>
<uses-permission android:name="android.permission.INTERNET"/>