安卓okhttp3与服务器通过json数据交互解析与上传
首先是安卓端,我主要上传一个User对象,下面是安卓端的代码通过okhttp3,gson编译成json格式上传
需要引用
compile 'com.google.code.gson:gson:2.8.1'
下面是客户端的一个功能的代码,主要将对象User上传给服务器,其中通过bundle将返回的对象传入到别的activity。本来想删除的,但是对于初学者应该还是很实用,gson.toJson()这个方法就是将user对象编译成json格式的字符串,方便上传给服务器
[html] view plain copy
- /**
- * 发送post请求
- */
- public User user = new User();
- public void postRequest(){
- OkHttpClient client = new OkHttpClient();
- user.setUsername(username.getText().toString());
- user.setPassword(content.getText().toString());
- Gson gson = new Gson();
- //使用Gson将对象转换为json字符串
- String json = gson.toJson(user);
- RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8")
- , json);
- Request request = new Request.Builder()
- .url(httpURL+"/HttpWeb/LoginServlet")//请求的url
- .post(requestBody)
- .build();
- Call call = client.newCall(request);
- call.enqueue(new Callback() {
- @Override
- public void onFailure(Call call, IOException e) {
- }
- @Override
- public void onResponse(Call call, Response response) throws IOException {
- final String res = response.body().string();
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- resultTV.setText(res);
- Log.v("Main.id=",res);
- if (!res.equals(null)){
- Toast.makeText(Main.this,"登陆成功",Toast.LENGTH_SHORT).show();
- user.setId(res);
- Intent intent = new Intent();
- intent.setClass(Main.this,MainActivity.class);//跳转到加载界面
- Bundle bundle = new Bundle();
- bundle.putParcelable("user", user);
- intent.putExtras(bundle);
- startActivity(intent);
- }else{
- Toast.makeText(Main.this,"登陆失败",Toast.LENGTH_SHORT).show();
- }
- }
- });
- }
- });
- }
User表,其中实现接口Parcelable是为了让bundle可以传递这个对象,使用bundle.putParcelable()这个办法
[html] view plain copy
- import android.os.Parcel;
- import android.os.Parcelable;
- import java.io.Serializable;
- /**
- * Created by acer1 on 2018/4/5.
- */
- public class User implements Parcelable,Serializable{
- private String id;
- private String username;
- private String password;
- private String Nickname;
- private String Individuality_signature;
- public User(Parcel in) {
- id = in.readString();
- username = in.readString();
- password = in.readString();
- }
- public static final Creator<User> CREATOR = new Creator<User>() {
- @Override
- public User createFromParcel(Parcel in) {
- return new User(in);
- }
- @Override
- public User[] newArray(int size) {
- return new User[size];
- }
- };
- public User() {
- }
- public String getNickname() {
- return Nickname;
- }
- public void setNickname(String nickname) {
- Nickname = nickname;
- }
- public String getIndividuality_signature() {
- return Individuality_signature;
- }
- public void setIndividuality_signature(String individuality_signature) {
- Individuality_signature = individuality_signature;
- }
- public String getId() {
- return id;
- }
- public void setId(String id) {
- this.id = id;
- }
- public String getUsername() {
- return username;
- }
- public void setUsername(String username) {
- this.username = username;
- }
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- @Override
- public int describeContents() {
- return 0;
- }
- @Override
- public void writeToParcel(Parcel dest, int flags) {
- dest.writeString(id);
- dest.writeString(username);
- dest.writeString(password);
- }
- }
现在客户端基本就完事了,下面是服务器的代码,我开始学的时候就主要想学怎么接收json格式的数据,我相信大家也是想学怎么接收json数据格式的数据,通过gson将接收的数据解析成对象,看代码。我们还要在服务器里面写一个javabean,让json数据映射成这个javabean,方便提取数据
首先我们导入一些包,让我们可以接收到json数据
[html] view plain copy
- protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
- response.setContentType("application/json");
- response.setCharacterEncoding("UTF-8");
- request.setCharacterEncoding("UTF-8");
- /**
- * 接收json
- */
- BufferedReader reader = request.getReader();
- String json = reader.readLine();
- System.out.println(json);
- Gson gson =new Gson();
- User user = gson.fromJson(json, User.class);
- System.out.println(user.getUsername());
- System.out.println(user.getPassword());
- PrintWriter out = response.getWriter();
- Integer msg;
- try {
- msg = UserDao.selectUser(user);
- out.print(msg);
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- reader.close();
- }
其中提取json数据和解析的代码就是下面这段代码
[html] view plain copy
- response.setContentType("application/json");
- response.setCharacterEncoding("UTF-8");
- request.setCharacterEncoding("UTF-8");
- /**
- * 接收json
- */
- BufferedReader reader = request.getReader();
- String json = reader.readLine();
- System.out.println(json);
- Gson gson =new Gson();
- User user = gson.fromJson(json, User.class);
- System.out.println(user.getUsername());
- System.out.println(user.getPassword());
然后就是服务器端的javabean
[html] view plain copy
- public class User {
- private String id;
- private String username;
- private String password;
- private String Nickname;
- private String Individuality_signature;
- public String getNickname() {
- return Nickname;
- }
- public void setNickname(String nickname) {
- Nickname = nickname;
- }
- public String getIndividuality_signature() {
- return Individuality_signature;
- }
- public void setIndividuality_signature(String individuality_signature) {
- Individuality_signature = individuality_signature;
- }
- public String getId() {
- return id;
- }
- public void setId(String id) {
- this.id = id;
- }
- public String getUsername() {
- return username;
- }
- public void setUsername(String username) {
- this.username = username;
- }
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- }
到这里基本的过程就结束了,从安卓端上传json数据到服务器端解析json数据,将json数据解析成javabean对象。不知道对初学者有没有帮助,又不懂的可以直接@我,