网络框架Retrofit的Get请求

Retrofit(改良)框架是Square公司出品的目前非常流行的网络框架,效率高,实现简单,运用注解和动态代理,极大的简化了网络请求的繁琐步骤,非常适合处理REST ful(一种风格)网络请求.目前Retrofit版本是2(可以说是Square公司之前出品okhttp的升级版)

特点:
  • 性能好,处理快,使用简单.(速度比Volley更快)
  • 使用REST API非常方便
  • 支持NIO(新的IO API,可以替代标准的Java IO API)
  • Retrofit默认使用okhttp处理网络请求;
  • 默认使用Gson解析
搭建Retrofit2.0的环境:
1.在项目的build.gradle中添加依赖
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
compile 'com.squareup.retrofit2:converter-scalars:2.3.0'
compile 'com.github.bumptech.glide:glide:4.0.0-RC1'
前三个是他的依赖,最后一个是glide图片框架依赖
2.在项目的清单文件中添加网络权限
     < uses-permission android :name= "android.permission.INTERNET" />
//网络请求的方法返回call:"一共两个一个是Get请求验证登录,一个是Get请求图片"
public class ApiHome {
    private BaseService baseService;
    private static volatile ApiHome instance;

    public ApiHome(BaseService baseService) {
        this.baseService = baseService;
    }

    public ApiHome() {
    }

    public static ApiHome getInstance() {
        if (instance == null) {
            synchronized (ApiHome.class) {
                if (instance == null) {
                    instance = new ApiHome();
                }
            }
        }
        return instance;
    }

 public Call<ResponseBody> getData(String qq, String pwd) {  
	if (baseService == null) {            
		baseService = Home.getBaseService();        
	}        
	StringBuffer stringBuffer = new StringBuffer();        
	//http://169.254.34.113/users/Guolei1130        //拼接参数        
	stringBuffer.append(Constant.URL_BASE).append("web/").append("LoginServlet?")                
						.append("qq="+qq)                
						.append("&pwd=" + pwd);        
		return baseService.baseGetRequest(stringBuffer.toString());    
	}    
	public Call<ResponseBody> getImage() {        
		if (baseService == null) {            
			baseService = Home.getBaseService();        
		}        
		StringBuffer stringBuffer = new StringBuffer();        
		//http://169.254.34.113/images/2017-06-02/c591370512f1d14c96d72ab383b5d153.jpeg        
		//拼接参数        
		stringBuffer.append(Constant.IMAGE_URL).append("images/").append("2017-06-02/c591370512f1d14c96d72ab383b5d153.jpeg");        
		return baseService.baseGetImage(stringBuffer.toString());    
		}
	}
另外他需要一个接口来写他的Get请求的网址
public interface BaseService {
    //get请求
    @GET
    Call<ResponseBody> baseGetRequest(@Url String user);
    @GET
    Call<ResponseBody> baseGetImage(@Url String user);
}
然后通过类接收使之在请求类实现
public class Home {

    static Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(Constant.URL_BASE)
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    public static BaseService getBaseService() {
        return retrofit.create(BaseService.class);
    }
}
当然重要的还得获取他的网址
public final class Constant {

    public static final String BASE_URL="https://api.github.com/";
    public static final String IMAGE_URL="http://omsproductionimg.yangkeduo.com/";

    public static final String URL_BASE="http://169.254.125.233:8080/";
}
最后在MainActivity中来给他吧数据展示
@Override
public void onClick(View view) {
    switch (view.getId()) {
        case R.id.button_get_reg://这个是展示Get请求登入页面的
            String qq = name.getText().toString();
            String pwd = password.getText().toString();
            call = ApiHome.getInstance().getData(qq, pwd);
            call.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    try {
                        String result = response.body().string();
                        Toast.makeText(MainActivity.this, result, Toast.LENGTH_LONG).show();
                    } catch (IOException e) {
                        e.printStackTrace();}}
                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                }});
            break;
        case R.id.button_get_pic://这个是显示图片的
            imageCall = ApiHome.getInstance().getImage();
            imageCall.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    try {
                        byte[] be = response.body().bytes();
                        Bitmap bitmap = BitmapFactory.decodeByteArray(be, 0, be.length);
                        imageView_login.setImageBitmap(bitmap);
                        saveBitmapToSDCard(bitmap, response.body().string());
                        Toast.makeText(MainActivity.this, "保存成功", Toast.LENGTH_LONG).show();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }}
                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                }});
            break;
        case R.id.button_get_file:
            break;
    }}
//销毁
@Override
protected void onDestroy() {
    super.onDestroy();
    if (call != null) {
        call.cancel();
    }}
/**
 * 保存bitmap到SD卡
 *
 * @param bitmap
 * @param imagename
 */
public static String saveBitmapToSDCard(Bitmap bitmap, String imagename) {
    String path = "/sdcard/" + "img-" + imagename + ".jpg";
    FileOutputStream fos = null;
    try {
        fos = new FileOutputStream(path);
        if (fos != null) {
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fos);
            fos.close();
        }

        return path;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值