1.开发环境
客户端:Android Studio 3.0.1
服务端:Eclipse
2.客户端
(1)AS新建一个项目,然后要使用Retrofit2.0 添加依赖和权限
//retrofit2 依赖库
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
//Gson 数据解析器依赖库
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
//网络权限
(2)写一个请求的接口
package com.example.nn.retrofitexample2;
import java.util.List;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;
/**
* Created by nn on 2019/7/17.
*/
//完整的请求URL为:http://192.168.94.1:8080/retrofit/retrofitservice?retrofit=xx
public interface RetrofitRequest {
@GET("retrofit/retrofitservice")
//java对象列表
Call> getData(@Query("retrofit") String retrofit);
}
(3)编写一个实体类
package com.example.nn.retrofitexample2;
/**
* Created by nn on 2019/7/17.
*/
public class User {
private String name;
private String sex;
public User(String name,String sex) {
this.name = name;
this.sex = sex;
}
public String getName() {
return name;
}
public String getSex() {
return sex;
}
}
(4)编写MainActivity中的代码
package com.example.nn.retrofitexample2;
import android.os.*;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.IOException;
import java.util.List;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends AppCompatActivity {
private TextView mshow;
private Button mrequest;
public static final String API_SERVICE = "http://192.168.94.1:8080/";
private Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Bundle data = msg.getData();
String result = data.getString("result");
mshow.setText(result);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化控件
init();
mrequest.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(runnable).start(); //不能在UI线程中进行网络请求
}
});
}
private void init(){
mshow = (TextView)findViewById(R.id.show);
mrequest = (Button)findViewById(R.id.request);
}
//发送网络请求
private String request() throws IOException {
//创建Retrofit对象
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(API_SERVICE)
.addConverterFactory(GsonConverterFactory.create())
.build();
//创建网络接口实例
RetrofitRequest retrofitRequest = retrofit.create(RetrofitRequest.class);
//对发送请求进行封装
Call> call = retrofitRequest.getData("REQUEST");
//发送请求,获取请求的数据
List list = call.execute().body();
StringBuilder result = new StringBuilder();
//遍历List
for(User user:list){
result.append("姓名:"+user.getName()+" 性别:"+user.getSex()+"\n");
}
return result.toString();
}
//网络请求线程
Runnable runnable = new Runnable() {
@Override
public void run() {
try {
String result = request();
Message msg = new Message();
Bundle data = new Bundle();
data.putString("result", result);
msg.setData(data);
handler.sendMessage(msg);
} catch (IOException e) {
Log.e("request_erro", e.toString());
}
}
};
}
(5)activity_main.xml 的代码
3.服务端
(1)
打开eclipse建立一个动态的web项目,在src下面建立 一个 retrofit的包,在这个包里面建立一个servlet,名字为:retrofitservice
代码如下:
package com.example.service;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.example.entity.User;
import net.sf.json.JSONObject;
/**
* Servlet implementation class retrofitservice
*/
@WebServlet("/retrofitservice")
public class retrofitservice extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public retrofitservice() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
List list = new ArrayList();
User user1 = new User("wenjian","man");
User user2 = new User("liwu","man");
User user3 = new User("张天","男");
list.add(user1);
list.add(user2);
list.add(user3);
//获得请求的数据
String message = request.getParameter("retrofit");
if (message.equals("REQUEST")) {
//JAVA对象列表转为JSON对象数组,然后转为JSON字符串
JSONArray jsonArray = JSONArray.fromObject(list);
message = jsonArray.toString();
}
System.out.println(message);
//返回数据
response.getWriter().append(message);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
(2)
实体类的代码
package com.example.entity;
public class User {
private String name;
private String sex;
public User() {
}
public User(String name, String sex) {
this.name = name;
this.sex = sex;
}
public String getName() {
return name;
}
public String getSex() {
return sex;
}
public void setName(String name) {
this.name = name;
}
public void setSex(String sex) {
this.sex = sex;
}
}
4.JAVA对象和JSON的转换
JSON字符串与java对象的转换
(1) 把java对象列表转换为json对象数组,并转为字符串
JSONArray array = JSONArray.fromObject(list);
String jsonstr = array.toString();
(2) 把java对象转换成json对象,并转化为字符串
JSONObject object = JSONObject.fromObject(user);
Log4jInit.ysulogger.debug(object.toString());
(3) 把JSON字符串转换为JAVA对象数组
JSONArray json = JSONArray.fromObject(userStr);//userStr是json字符串
List
(4) 把JSON字符串转换为JAVA 对象
JSONObject jsonobject = JSONObject.fromObject(jsonStr);
User user= (User)JSONObject.toBean(object,User.class);
5.JSON所需的包
链接:https://pan.baidu.com/s/1Q8LNwn151VDkGPPGgWWgPw
提取码:mv8w
复制这段内容后打开百度网盘手机App,操作更方便哦
6.项目结构
7.运行结果