使用
添加依赖
implementation 'com.loopj.android:android-async-http:1.4.9'
写了一个单例模式
package com.example.asynhttp;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.widget.ImageView;
import android.widget.TextView;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.BinaryHttpResponseHandler;
import com.loopj.android.http.PersistentCookieStore;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import cz.msebera.android.httpclient.Header;
import cz.msebera.android.httpclient.cookie.Cookie;
import cz.msebera.android.httpclient.impl.cookie.BasicClientCookie;
public class Danli {
//单利模式 吃对象在内存中允许只有一个
public static Danli sDanli=null;
private static AsyncHttpClient clitnt=null;
private static PersistentCookieStore cookieStore=null;
public static Danli initnst(Context c){
if(sDanli==null){
sDanli= new Danli();
clitnt=new AsyncHttpClient();//当上面实例化了我也就实例化能用了
cookieStore= new PersistentCookieStore(c);
return sDanli;
}
return sDanli;
}
public void setText(Context context, final TextView tv){
RequestParams requestParams = new RequestParams();
requestParams.put("key","cef62c58401d7bfa7d4f6daab78a8d68");
clitnt.post(context,
"http://v.juhe.cn/joke/randJoke.php",
requestParams,
new TextHttpResponseHandler() {
@Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
}
@Override
public void onSuccess(int statusCode, Header[] headers, String responseString) {
tv.setText(responseString);
}
}
);
}
public void setImage(Context context, final ImageView view){
clitnt.get(
"https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1534158873&di=aba3dbf2f2fb6d0868b72e56ec24293e&src=http://img5.duitang.com/uploads/item/201510/24/20151024001812_j3S8P.jpeg",
new BinaryHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] binaryData) {
File file = new File(Environment.getExternalStorageDirectory()+"/wode1223.jpeg");
try {
FileOutputStream fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(binaryData);
fileOutputStream.flush();
fileOutputStream.close();
// view.setImageBitmap(BitmapFactory.decodeByteArray(binaryData,0,binaryData.length));
// view.setImageBitmap(BitmapFactory.decodeFile(String.valueOf(file)));
view.setImageBitmap(BitmapFactory.decodeFile(file.getAbsolutePath()));
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] binaryData, Throwable error) {
}
}
);
}
public void storeData(String data){
//保存到内存中,会保存应用的信息,相当于getSharedPreferences
BasicClientCookie newCookie = new BasicClientCookie("name", "value");
newCookie.setVersion(1);
newCookie.setDomain(Environment.getExternalStorageDirectory().toString());
newCookie.setValue(data);
cookieStore.addCookie(newCookie);
}
public void getDataByCookie(TextView tx){
final TextView textView = tx;
Cookie newCookie = cookieStore.getCookies().get(0);
//字符串截取 subString()
textView.setText("获取的cookie数据:"+newCookie.getValue());
}
// public void netWorkDownFile(final ImageView imageView){
// clitnt.get(
// "https://ss0.bdstatic.com/94oJfD_bAAcT8t7mm9GUKT-xh_/timg?image&quality=100&size=b4000_4000&sec=1534158873&di=aba3dbf2f2fb6d0868b72e56ec24293e&src=http://img5.duitang.com/uploads/item/201510/24/20151024001812_j3S8P.jpeg"
// , new BinaryHttpResponseHandler() {
// @Override
// public void onSuccess(int statusCode, Header[] headers, byte[] binaryData) {
// File file = new File(Environment.getExternalStorageDirectory()+"/my2.jpeg");
//// File file = new File(Environment.getExternalStorageDirectory(),"my.jpeg");
// try {
// FileOutputStream fileOutputStream = new FileOutputStream(file);
// fileOutputStream.write(binaryData);
// fileOutputStream.flush();
// fileOutputStream.close();
// imageView.setImageBitmap(BitmapFactory.decodeFile(String.valueOf(file)));//将File转换成路径
//// ig.setImageBitmap(BitmapFactory.decodeFile(file.getAbsolutePath()));
// } catch (Exception e) {
// e.printStackTrace();
// }
// }
//
// @Override
// public void onFailure(int statusCode, Header[] headers, byte[] binaryData,
// Throwable error) {
//
// }
// });
// }
private Danli(){}
}
MainActivity
package com.example.asynhttp;
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cz.msebera.android.httpclient.Header;
public class MainActivity extends AppCompatActivity {
@BindView(R.id.main_get)//相当于FindViewByid
Button mMainGet;
@BindView(R.id.main_post)
Button mMainPost;
@BindView(R.id.select_image)
Button mSelectImage;
@BindView(R.id.main_image)
ImageView mMainImage;
@BindView(R.id.content)
TextView mContent;
@BindView(R.id.content2)
TextView mContent2;
private Danli mInitnst;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
mInitnst = Danli.initnst(this);
}
@OnClick({R.id.main_get, R.id.main_post, R.id.select_image})
public void onViewClicked(View view) {
switch (view.getId()) {
case R.id.main_get:
getAsynHttp();
mInitnst.getDataByCookie(mContent2);
break;
case R.id.main_post:
postAsynHttp();
break;
case R.id.select_image:
setPermissions();
mInitnst.storeData("我是cookie");
// initnst.setText(this,mContent);
// initnst.netWorkDownFile(mMainImage);
mInitnst.setImage( mMainImage);
break;
}
}
private void postAsynHttp() {
AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
RequestParams requestParams = new RequestParams();
requestParams.put("key", "cef62c58401d7bfa7d4f6daab78a8d68");
asyncHttpClient.post(this,
"http://v.juhe.cn/joke/randJoke.php",
requestParams, new TextHttpResponseHandler() {
@Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
}
@Override
public void onSuccess(int statusCode, Header[] headers, String responseString) {
mContent.setText(responseString);
}
});
}
void getAsynHttp() {
//创建对象
AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
//get联网方式
asyncHttpClient.get(
"http://v.juhe.cn/joke/randJoke.php?key=cef62c58401d7bfa7d4f6daab78a8d68",
new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
mContent.setText("获取的值:" + new String(responseBody, 0, responseBody.length));
}
@Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
}
}
);
}
static final String[] PERMISSION = new String[]{
Manifest.permission.WRITE_EXTERNAL_STORAGE,// 写入权限
Manifest.permission.READ_EXTERNAL_STORAGE, //读取权限
Manifest.permission.INTERNET //读取设备信息
};
private void setPermissions() {
if (ContextCompat.checkSelfPermission(MainActivity.this,
PERMISSION[0]) != PackageManager.PERMISSION_GRANTED) {
Log.d("data", "权限申请");
Toast.makeText(this, "申请权限", Toast.LENGTH_SHORT).show();
//Android 6.0申请权限
ActivityCompat.requestPermissions(this, PERMISSION, 1);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,
int[] grantResults) {
if (requestCode == 1) {
if (ContextCompat.checkSelfPermission(MainActivity.this,
PERMISSION[0]) == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "写入申请成功", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "写入申请失败", Toast.LENGTH_SHORT).show();
}
if (ContextCompat.checkSelfPermission(MainActivity.this,
PERMISSION[1]) == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "读取申请成功", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "读取申请失败", Toast.LENGTH_SHORT).show();
}
if (ContextCompat.checkSelfPermission(MainActivity.this,
PERMISSION[2]) == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "联网申请成功", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "联网申请失败", Toast.LENGTH_SHORT).show();
}
}
}
}