retrofit的get请求

1 金山词霸 注:转载别人的
首先加入网络权限和允许明文
在这里插入图片描述

接口说明:

/**
 * URL模板
 * http://fy.iciba.com/ajax.php
 *
 * // URL实例
 * // http://fy.iciba.com/ajax.php?a=fy&f=auto&t=auto&w=hello%20world
 *
 * // 参数说明:
 * // a:固定值 fy
 * // f:原文内容类型,日语取 ja,中文取 zh,英语取 en,韩语取 ko,德语取 de,西班牙语取 es,法语取 fr,自动则取 auto
 * // t:译文内容类型,日语取 ja,中文取 zh,英语取 en,韩语取 ko,德语取 de,西班牙语取 es,法语取 fr,自动则取 auto
 * // w:查询内容
 */

在这里插入图片描述
按照API响应格式创建的类:(gsonformat插件就是一个很好地东西)

package com.example.retrofit;

public class Translation {
    private int status;
    private content content;

    private static class content {
        private String from;
        private String to;
        private String vendor;
        private String out;
        private int errNo;
    }

    //定义 输出返回数据 的方法
    public void show() {
        System.out.println(status);
        System.out.println(content.from);
        System.out.println(content.to);
        System.out.println(content.vendor);
        System.out.println(content.out);
        System.out.println(content.errNo);
    }
}

创建网络接口

public interface GetRequest_Interface {
    
 @GET("ajax.php?a=fy&f=auto&t=auto&w=hello%20world")
    Call<Translation> getCall();
    // 注解里传入 网络请求 的部分URL地址
    // Retrofit把网络请求的URL分成了两部分:一部分放在Retrofit对象里,另一部分放在网络请求接口里
    // 如果接口里的url是一个完整的网址,那么放在Retrofit对象里的URL可以忽略
    // getCall()是接受网络请求数据的方法
}
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = findViewById(R.id.get);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                get(v);
            }
        });
    }
    public void get(View view) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://fy.iciba.com") //baseurl,具体接口在接口里
                .addConverterFactory(GsonConverterFactory.create()) //设置使用Gson解析
                .build();
        GetRequest_Interface request = retrofit.create(GetRequest_Interface.class);
        Call<Translation> call = request.getCall();
        //采用异步方法
        call.enqueue(new Callback<Translation>(){
            @Override
            public void onResponse(Call<Translation> call, Response<Translation> response) {
                if(response.isSuccessful()) {
                    Translation bean1 = response.body();  //body值为null
                    Log.d("Tag ------------>","successful!");
                    Log.d("Tag ------------>",bean1.toString());
                    bean1.show();
                }
                else
                    System.out.println("response is failed");
            }
            @Override
            public void onFailure(Call<Translation> call, Throwable throwable) {
            }
        });
    }
}

在这里插入图片描述

2 自己搭建的一个简易服务器(Django)。
先看Django部分:

	URl:http://192.168.163.1:8000/hello          
	注: path('hello/',views.hello),
	有一个模型:
	class User(models.Model):
			name = models.CharField(max_length=20)
			password = models.CharField(max_length=10)
	一个类转字典的函数(为了将类对象转化成json)
	def usertojson(user):
		  return {'name':user.name,'password':user.password}
	映射的view:
	def hello(request):
		    user = User(name="retrofit", password="password")
		    user_json=json.dumps(user,default=usertojson) #user是类,default是转化函数
		    print(user_json)
		    return HttpResponse(user_json)

再看android部分:
创建类:

public class userss {
    /**
     * name : retrofit
     * password : password
     * 此处省略get (), set()方法
     */
    private String name;
    private String password;

retrofit的接口类:

public interface GetRequest_Interface {
@GET("hello")
Call<userss> getCall();

}

主要活动:

    public void get(View view) {
        System.out.println("从把手机勃而不佛IE欺负你企鹅哦覅偶");
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://192.168.163.1:8000/")
                .addConverterFactory(GsonConverterFactory.create()) //设置使用Gson解析
                .build();
        GetRequest_Interface request = retrofit.create(GetRequest_Interface.class);
        Call<userss> call = request.getCall();
        call.enqueue(new Callback<userss>(){

            @Override
            public void onResponse(Call<userss> call, Response<userss> response) {
                if(response.isSuccessful()) {
                    Log.d("Tag------------------>",String.valueOf(response.code()));
                    Log.d("Tag------------------>",response.body().toString());
                }
                else
                    System.out.println("response is failed");
            }
            @Override
            public void onFailure(Call<userss> call, Throwable throwable) {
                System.out.println(throwable.getMessage());
                Log.d("Tag------------------>","error");
            }
        });
    }

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值