import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
private ListView listView;
private TextView textView;
private AsyncTask asyncTask;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listview);
textView = (TextView) findViewById(R.id.textview);
// asyncTask();
//enqueue();
postEnqueue();
}
private void postEnqueue() {
OkHttpClient client = new OkHttpClient.Builder()
.readTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10,TimeUnit.SECONDS)
.connectTimeout(10,TimeUnit.SECONDS)
.build();
RequestBody requestBody = new FormBody.Builder()
.add("pscid","39")
.add("page","1")
.build();
Request request = new Request.Builder().url("http://120.27.23.105/product/getProducts")
.post(requestBody)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(MainActivity.this,"1111",Toast.LENGTH_SHORT).show();
}
});
Log.i("------",response.body().string());
}
});
}
private void enqueue() {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder().url("http://120.27.23.105/product/getProducts?pscid=39&page=1").build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
// System.out.println();
String string = response.body().string();
Log.i("---",string);
}
});
}
private void asyncTask() {
asyncTask = new AsyncTask() {
@Override
protected String doInBackground(Void... voids) {
String path ="http://120.27.23.105/product/getProducts?pscid=39&page=1";
try {
URL url = new URL(path);
HttpURLConnection cOnnection= (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setReadTimeout(5000);
connection.setConnectTimeout(5000);
int respOnseCode= connection.getResponseCode();
if (respOnseCode==200){
InputStream inputStream = connection.getInputStream();
String s = stringStream(inputStream,"utf-8");
// Log.i("---------sas----------",s);
return s;
}
} catch (Exception e) {
e.printStackTrace();
}
return "saasas";
}
@Override
protected void onPostExecute(String st) {
super.onPostExecute(st);
// Log.i("-------------------",st);
Gson gson = new Gson();
DataDataBean dataDataBean = gson.fromJson(st, DataDataBean.class);
List list = dataDataBean.getData();
MyAdapter myAdapter = new MyAdapter(list, MainActivity.this);
listView.setAdapter(myAdapter);
}
};
asyncTask.execute();
}
private String stringStream(InputStream inputStream, String s) {
try {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, s);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String string = null;
StringBuilder stringBuilder = new StringBuilder();
while ((string = bufferedReader.readLine())!=null){
stringBuilder.append(string);
}
bufferedReader.close();
return stringBuilder.toString();
} catch (Exception e) {
e.printStackTrace();
}
return s;
}
}
//适配器
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.nostra13.universalimageloader.core.ImageLoader;
import java.util.List;
/**
* Created by MK on 2017/11/1.
*/
public class MyAdapter extends BaseAdapter{
List list;
private int left=0;
private int rigeht=1;
Context context;
public MyAdapter(List list, Context context) {
this.list=list;
this.context=context;
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int i) {
return list.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public int getViewTypeCount() {
return 2;
}
@Override
public int getItemViewType(int position) {
if (position%2==0){
return left;
}
return rigeht;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (getItemViewType(i)==left){
ViewHolder01 holder;
if (view==null){
view = View.inflate(context,R.layout.left_item,null);
holder = new ViewHolder01();
holder.text01 = (TextView) view.findViewById(R.id.text01);
holder.image01 = (ImageView) view.findViewById(R.id.image01);
view.setTag(holder);
}else {
holder = (ViewHolder01) view.getTag();
}
holder.text01.setText(list.get(i).getTitle());
ImageLoader.getInstance().displayImage(list.get(i).getImages(),holder.image01, ImageLoaderUtil.getoption());
}else if (getItemViewType(i)==rigeht){
ViewHolder02 holder;
if (view==null){
view = View.inflate(context,R.layout.right,null);
holder = new ViewHolder02();
holder.text01 = (TextView) view.findViewById(R.id.text01);
view.setTag(holder);
}else {
holder = (ViewHolder02) view.getTag();
}
holder.text01.setText(list.get(i).getTitle());
}
return view;
}
class ViewHolder01{
TextView text01;
ImageView image01;
}
class ViewHolder02{
TextView text01;
}
}
//imageloder
import android.app.Application;
/**
* Created by MK on 2017/11/1.
*/
public class ImageLoader extends Application{
@Override
public void onCreate() {
super.onCreate();
ImageLoaderUtil.getInit(this);
}
}
//设置
import android.content.Context;
import android.graphics.Bitmap;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiskCache;
import com.nostra13.universalimageloader.cache.disc.naming.HashCodeFileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.core.*;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.decode.BaseImageDecoder;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import com.nostra13.universalimageloader.utils.StorageUtils;
import java.io.File;
/**
* Created by MK on 2017/11/1.
*/
public class ImageLoaderUtil {
public static void getInit(Context context) {
File cacheDir = StorageUtils.getCacheDirectory(context); //缓存文件夹路径
ImageLoaderConfiguration cOnfig= new ImageLoaderConfiguration.Builder(context)
.memoryCacheExtraOptions(480, 800) // default = device screen dimensions 内存缓存文件的最大长宽
.diskCacheExtraOptions(480, 800, null) // 本地缓存的详细信息(缓存的最大长宽),最好不要设置这个
.threadPoolSize(3) // default 线程池内加载的数量
.threadPriority(Thread.NORM_PRIORITY - 2) // default 设置当前线程的优先级
.tasksProcessingOrder(QueueProcessingType.FIFO) // default
.denyCacheImageMultipleSizesInMemory()
.memoryCache(new LruMemoryCache(2 * 1024 * 1024)) //可以通过自己的内存缓存实现
.memoryCacheSize(2 * 1024 * 1024) // 内存缓存的最大值
.memoryCacheSizePercentage(13) // default
.diskCache(new UnlimitedDiskCache(cacheDir)) // default 可以自定义缓存路径
.diskCacheSize(50 * 1024 * 1024) // 50 Mb sd卡(本地)缓存的最大值
.diskCacheFileCount(100) // 可以缓存的文件数量
// default为使用HASHCODE对UIL进行加密命名, 还可以用MD5(new Md5FileNameGenerator())加密
.diskCacheFileNameGenerator(new HashCodeFileNameGenerator())
.imageDownloader(new BaseImageDownloader(context)) // default
.imageDecoder(new BaseImageDecoder(true)) // default
.defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default
.writeDebugLogs() // 打印debug log
.build(); //开始构建
com.nostra13.universalimageloader.core.ImageLoader.getInstance().init(config);
}
public static DisplayImageOptions getoption() {
DisplayImageOptions options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.mipmap.ic_launcher) // 设置图片下载期间显示的图片
.showImageForEmptyUri(R.mipmap.ic_launcher) // 设置图片Uri为空或是错误的时候显示的图片
.showImageOnFail(R.mipmap.ic_launcher) // 设置图片加载或解码过程中发生错误显示的图片
.resetViewBeforeLoading(false) // default 设置图片在加载前是否重置、复位
.delayBeforeLoading(1000) // 下载前的延迟时间
.cacheInMemory(false) // default 设置下载的图片是否缓存在内存中
.cacheOnDisk(false) // default 设置下载的图片是否缓存在SD卡中
.considerExifParams(false) // default
.imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2) // default 设置图片以如何的编码方式显示
.bitmapConfig(Bitmap.Config.ARGB_8888) // default 设置图片的解码类型
// 图片的解码设置
// default 还可以设置圆角图片new RoundedBitmapDisplayer(20)
.build();
return options;
}
}