参考:https://blog.youkuaiyun.com/carson_ho/article/details/73732076
常量类
public class constant {
// URL模板
public static String url1= "http://fy.iciba.com/ajax.php";
// URL实例
public static String url2="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:查询内容
}
接收服务器返回的类
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("");
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(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void btn(View view){
System.out.println("ThreadName="+Thread.currentThread().getName());
request();
}
public static void request() {
//步骤4:创建Retrofit对象
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://fy.iciba.com/") // 设置 网络请求 Url
.addConverterFactory(GsonConverterFactory.create()) //设置使用Gson解析(记得加入依赖)
.build();
// 步骤5:创建 网络请求接口 的实例
GetRequest_Interface request = retrofit.create(GetRequest_Interface.class);
//对 发送请求 进行封装
Call<Translation> call = request.getCall();
//步骤6:发送网络请求(异步)
call.enqueue(new Callback<Translation>() {
//请求成功时回调
@Override
public void onResponse(Call<Translation> call, Response<Translation> response) {
// 步骤7:处理返回的数据结果
response.body().show();
System.out.println("ThreadName ="+Thread.currentThread().getName());
}
//请求失败时回调
@Override
public void onFailure(Call<Translation> call, Throwable throwable) {
System.out.println("连接失败");
}
});
}
}
深入理解Java虚拟机
链接: https://pan.baidu.com/s/1APHmaV6JJUwis9V-fWlpkQ 密码: 8jz3