网络框架有很多,Okhttp是比较出名的一个,参考宏洋大神博客,写下自己的笔记,供参考
1.首先gradle,没什么好说的,就是依赖这几个,因为用的是别人封装过的okhttp
compile ‘com.squareup.okhttp:okhttp:2.4.0’
compile ‘com.squareup.okio:okio:1.5.0’
compile ‘com.google.code.gson:gson:2.6.2’
2.Activity中的代码
package com.caobo.okhttptest;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import com.caobo.okhttptest.GsonTest.Person;
import com.caobo.okhttptest.okhttpUility.OkHttpClientManager;
import com.squareup.okhttp.Request;
import java.util.List;
/**
* 1.以上就是发送一个get请求的步骤,首先构造一个Request对象,参数最起码有个url
* 2.然后通过request的对象去构造得到一个Call对象,类似于将你的请求封装成了任务,既然是任务,就会有execute()和cancel()等方法
* 3.最后,我们希望以异步的方式去执行请求,所以我们调用的是call.enqueue,将call加入调度队列,然后等待任务执行完成,我们在Callback中即可得到结果
* 4.每次请求还是比较麻烦的,所以我们自己还是要封装一下
*
* eg:"http://www.weather.com.cn/data/list3/city.xml"
*/
public class MainActivity extends Activity {
private TextView mTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextView = (TextView) findViewById(R.id.test);
//okHttp发送网络Get请求,注意这里我们指定的是String类型如:.ResultCallback<String>
OkHttpClientManager.getAsyn("http://www.weather.com.cn/data/list3/city.xml", new OkHttpClientManager.ResultCallback<String>() {
@Override
public void onError(Request request, Exception e) {
e.printStackTrace();
}
@Override
public void onResponse(String response) {
//注意这里是Ui线程
//mTextView.setText(response);
}
});
//http://www.imooc.com/api/teacher?type=4&num=30
//整合的Gson,暂时不会用,解析不出来
OkHttpClientManager.getAsyn("http://www.imooc.com/api/teacher?type=4&num=30",
new OkHttpClientManager.ResultCallback<List<Person>>()
{
@Override
public void onError(Request request, Exception e)
{
e.printStackTrace();
}
@Override
public void onResponse(List<Person> us)
{
Log.e("TAG", us.size() + "");
mTextView.setText(us.get(1).getMsg());
}
});
}
}
3.封装类,直接贴代码
这个是处理图片用的,目前我没有用的到,只测试了get请求
ImageUtils.java
package com.caobo.okhttptest.okhttpUility;
import android.graphics.BitmapFactory;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import java.io.InputStream;
import java.lang.reflect.Field;
/**
* Created by zhy on 15/11/6.
*/
public class ImageUtils
{
/**
* 根据InputStream获取图片实际的宽度和高度
*
* @param imageStream
* @return
*/
public static ImageSize getImageSize(InputStream imageStream)
{
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(imageStream, null, options);
return new ImageSize(options.outWidth, options.outHeight);
}
public static class ImageSize
{
int width;
int height;
public ImageSize()
{
}
public ImageSize(int width, int height)
{
this.width = width;
this.height = height;
}
@Override
public String toString()
{
return "ImageSize{" +
"width=" + width +
", height=" + height +
'}';
}
}
public static int calculateInSampleSize(ImageSize srcSize, ImageSize targetSize)
{
// 源图片的宽度
int width = srcSize.width;
int height = srcSize.height;
int inSampleSize = 1;
int reqWidth = targetSize.width;
int reqHeight = targetSize.height;
if (width > reqWidth && height > reqHeight)
{
// 计算出实际宽度和目标宽度的比率
int widthRatio = Math.round((float) width / (float) reqWidth);
int heightRatio = Math.round((float) height / (float) reqHeight);
inSampleSize = Math.max(widthRatio, heightRatio);
}
return inSampleSize;
}
/**
* 根据ImageView获适当的压缩的宽和高
*
* @param view
* @return
*/
public static ImageSize getImageViewSize(View view)
{
ImageSize imageSize = new ImageSize();
imageSize.width = getExpectWidth(view);
imageSize.height = getExpectHeight(view);
return imageSize;
}
/**
* 根据view获得期望的高度
*
* @param view
* @return
*/
private static int getExpectHeight(View view)
{
int height = 0;
if (view == null) return 0;
final ViewGroup.LayoutParams params = view.getLayoutParams();
//如果是WRAP_CONTENT,此时图片还没加载,getWidth根本无效
if (params != null && params.height != ViewGroup.LayoutParams.WRAP_CONTENT)
{
height = view.getWidth(); // 获得实际的宽度
}
if (height <= 0 && params != null)
{
height = params.height; // 获得布局文件中的声明的宽度
}
if (height <= 0)
{
height = getImageViewFieldValue(view, "mMaxHeight");// 获得设置的最大的宽度
}
//如果宽度还是没有获取到,憋大招,使用屏幕的宽度
if (height <= 0)
{
DisplayMetrics displayMetrics = view.getContext().getResources()
.getDisplayMetrics();
height = displayMetrics.heightPixels;
}
return height;
}
/**
* 根据view获得期望的宽度
*
* @param view
* @return
*/
private static int getExpectWidth(View view)
{
int width = 0;
if (view == null) return 0;
final ViewGroup.LayoutParams params = view.getLayoutParams();
//如果是WRAP_CONTENT,此时图片还没加载,getWidth根本无效
if (params != null && params.width != ViewGroup.LayoutParams.WRAP_CONTENT)
{
width = view.getWidth(); // 获得实际的宽度
}
if (width <= 0 && params != null)
{
width = params.width; // 获得布局文件中的声明的宽度
}
if (width <= 0)
{
width = getImageViewFieldValue(view, "mMaxWidth");// 获得设置的最大的宽度
}
//如果宽度还是没有获取到,憋大招,使用屏幕的宽度
if (width <= 0)
{
DisplayMetrics displayMetrics = view.getContext().getResources()
.getDisplayMetrics();
width = displayMetrics.widthPixels;
}
return width;
}
/**
* 通过反射获取imageview的某个属性值
*
* @param object
* @param fieldName
* @return
*/
private static int getImageViewFieldValue(Object object, String fieldName)
{
int value = 0;
try
{
Field field = ImageView.class.getDeclaredField(fieldName);
field.setAccessible(true);
int fieldValue = field.getInt(object);
if (fieldValue > 0 && fieldValue < Integer.MAX_VALUE)
{
value = fieldValue;
}
} catch (Exception e)
{
}
return value;
}
}
OkHttpClientManager.java
package com.caobo.okhttptest.okhttpUility;
import android.graphics.BitmapFactory;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import java.io.InputStream;
import java.lang.reflect.Field;
/**
* Created by zhy on 15/11/6.
*/
public class ImageUtils
{
/**
* 根据InputStream获取图片实际的宽度和高度
*
* @param imageStream
* @return
*/
public static ImageSize getImageSize(InputStream imageStream)
{
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(imageStream, null, options);
return new ImageSize(options.outWidth, options.outHeight);
}
public static class ImageSize
{
int width;
int height;
public ImageSize()
{
}
public ImageSize(int width, int height)
{
this.width = width;
this.height = height;
}
@Override
public String toString()
{
return "ImageSize{" +
"width=" + width +
", height=" + height +
'}';
}
}
public static int calculateInSampleSize(ImageSize srcSize, ImageSize targetSize)
{
// 源图片的宽度
int width = srcSize.width;
int height = srcSize.height;
int inSampleSize = 1;
int reqWidth = targetSize.width;
int reqHeight = targetSize.height;
if (width > reqWidth && height > reqHeight)
{
// 计算出实际宽度和目标宽度的比率
int widthRatio = Math.round((float) width / (float) reqWidth);
int heightRatio = Math.round((float) height / (float) reqHeight);
inSampleSize = Math.max(widthRatio, heightRatio);
}
return inSampleSize;
}
/**
* 根据ImageView获适当的压缩的宽和高
*
* @param view
* @return
*/
public static ImageSize getImageViewSize(View view)
{
ImageSize imageSize = new ImageSize();
imageSize.width = getExpectWidth(view);
imageSize.height = getExpectHeight(view);
return imageSize;
}
/**
* 根据view获得期望的高度
*
* @param view
* @return
*/
private static int getExpectHeight(View view)
{
int height = 0;
if (view == null) return 0;
final ViewGroup.LayoutParams params = view.getLayoutParams();
//如果是WRAP_CONTENT,此时图片还没加载,getWidth根本无效
if (params != null && params.height != ViewGroup.LayoutParams.WRAP_CONTENT)
{
height = view.getWidth(); // 获得实际的宽度
}
if (height <= 0 && params != null)
{
height = params.height; // 获得布局文件中的声明的宽度
}
if (height <= 0)
{
height = getImageViewFieldValue(view, "mMaxHeight");// 获得设置的最大的宽度
}
//如果宽度还是没有获取到,憋大招,使用屏幕的宽度
if (height <= 0)
{
DisplayMetrics displayMetrics = view.getContext().getResources()
.getDisplayMetrics();
height = displayMetrics.heightPixels;
}
return height;
}
/**
* 根据view获得期望的宽度
*
* @param view
* @return
*/
private static int getExpectWidth(View view)
{
int width = 0;
if (view == null) return 0;
final ViewGroup.LayoutParams params = view.getLayoutParams();
//如果是WRAP_CONTENT,此时图片还没加载,getWidth根本无效
if (params != null && params.width != ViewGroup.LayoutParams.WRAP_CONTENT)
{
width = view.getWidth(); // 获得实际的宽度
}
if (width <= 0 && params != null)
{
width = params.width; // 获得布局文件中的声明的宽度
}
if (width <= 0)
{
width = getImageViewFieldValue(view, "mMaxWidth");// 获得设置的最大的宽度
}
//如果宽度还是没有获取到,憋大招,使用屏幕的宽度
if (width <= 0)
{
DisplayMetrics displayMetrics = view.getContext().getResources()
.getDisplayMetrics();
width = displayMetrics.widthPixels;
}
return width;
}
/**
* 通过反射获取imageview的某个属性值
*
* @param object
* @param fieldName
* @return
*/
private static int getImageViewFieldValue(Object object, String fieldName)
{
int value = 0;
try
{
Field field = ImageView.class.getDeclaredField(fieldName);
field.setAccessible(true);
int fieldValue = field.getInt(object);
if (fieldValue > 0 && fieldValue < Integer.MAX_VALUE)
{
value = fieldValue;
}
} catch (Exception e)
{
}
return value;
}
}
4,github地址:https://github.com/Androidcaobo/OkhttpTest
宏洋原博客:http://blog.csdn.net/lmj623565791/article/details/47911083