安卓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

  1. /**
  2. * 发送post请求
  3. */
  4. public User user = new User();
  5. public void postRequest(){
  6. OkHttpClient client = new OkHttpClient();
  7. user.setUsername(username.getText().toString());
  8. user.setPassword(content.getText().toString());
  9. Gson gson = new Gson();
  10. //使用Gson将对象转换为json字符串
  11. String json = gson.toJson(user);
  12. RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8")
  13. , json);
  14. Request request = new Request.Builder()
  15. .url(httpURL+"/HttpWeb/LoginServlet")//请求的url
  16. .post(requestBody)
  17. .build();
  18. Call call = client.newCall(request);
  19. call.enqueue(new Callback() {
  20. @Override
  21. public void onFailure(Call call, IOException e) {
  22. }
  23. @Override
  24. public void onResponse(Call call, Response response) throws IOException {
  25. final String res = response.body().string();
  26. runOnUiThread(new Runnable() {
  27. @Override
  28. public void run() {
  29. resultTV.setText(res);
  30. Log.v("Main.id=",res);
  31. if (!res.equals(null)){
  32. Toast.makeText(Main.this,"登陆成功",Toast.LENGTH_SHORT).show();
  33. user.setId(res);
  34. Intent intent = new Intent();
  35. intent.setClass(Main.this,MainActivity.class);//跳转到加载界面
  36. Bundle bundle = new Bundle();
  37. bundle.putParcelable("user", user);
  38. intent.putExtras(bundle);
  39. startActivity(intent);
  40. }else{
  41. Toast.makeText(Main.this,"登陆失败",Toast.LENGTH_SHORT).show();
  42. }
  43. }
  44. });
  45. }
  46. });
  47. }

User表,其中实现接口Parcelable是为了让bundle可以传递这个对象,使用bundle.putParcelable()这个办法

[html] view plain copy

  1. import android.os.Parcel;
  2. import android.os.Parcelable;
  3. import java.io.Serializable;
  4. /**
  5. * Created by acer1 on 2018/4/5.
  6. */
  7. public class User implements Parcelable,Serializable{
  8. private String id;
  9. private String username;
  10. private String password;
  11. private String Nickname;
  12. private String Individuality_signature;
  13. public User(Parcel in) {
  14. id = in.readString();
  15. username = in.readString();
  16. password = in.readString();
  17. }
  18. public static final Creator<User> CREATOR = new Creator<User>() {
  19. @Override
  20. public User createFromParcel(Parcel in) {
  21. return new User(in);
  22. }
  23. @Override
  24. public User[] newArray(int size) {
  25. return new User[size];
  26. }
  27. };
  28. public User() {
  29. }
  30. public String getNickname() {
  31. return Nickname;
  32. }
  33. public void setNickname(String nickname) {
  34. Nickname = nickname;
  35. }
  36. public String getIndividuality_signature() {
  37. return Individuality_signature;
  38. }
  39. public void setIndividuality_signature(String individuality_signature) {
  40. Individuality_signature = individuality_signature;
  41. }
  42. public String getId() {
  43. return id;
  44. }
  45. public void setId(String id) {
  46. this.id = id;
  47. }
  48. public String getUsername() {
  49. return username;
  50. }
  51. public void setUsername(String username) {
  52. this.username = username;
  53. }
  54. public String getPassword() {
  55. return password;
  56. }
  57. public void setPassword(String password) {
  58. this.password = password;
  59. }
  60. @Override
  61. public int describeContents() {
  62. return 0;
  63. }
  64. @Override
  65. public void writeToParcel(Parcel dest, int flags) {
  66. dest.writeString(id);
  67. dest.writeString(username);
  68. dest.writeString(password);
  69. }
  70. }

现在客户端基本就完事了,下面是服务器的代码,我开始学的时候就主要想学怎么接收json格式的数据,我相信大家也是想学怎么接收json数据格式的数据,通过gson将接收的数据解析成对象,看代码。我们还要在服务器里面写一个javabean,让json数据映射成这个javabean,方便提取数据

首先我们导入一些包,让我们可以接收到json数据

安卓okhttp3与服务器通过json数据交互解析与上传

[html] view plain copy

  1. protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  2. response.setContentType("application/json");
  3. response.setCharacterEncoding("UTF-8");
  4. request.setCharacterEncoding("UTF-8");
  5. /**
  6. * 接收json
  7. */
  8. BufferedReader reader = request.getReader();
  9. String json = reader.readLine();
  10. System.out.println(json);
  11. Gson gson =new Gson();
  12. User user = gson.fromJson(json, User.class);
  13. System.out.println(user.getUsername());
  14. System.out.println(user.getPassword());
  15. PrintWriter out = response.getWriter();
  16. Integer msg;
  17. try {
  18. msg = UserDao.selectUser(user);
  19. out.print(msg);
  20. } catch (Exception e) {
  21. // TODO Auto-generated catch block
  22. e.printStackTrace();
  23. }
  24. reader.close();
  25. }

其中提取json数据和解析的代码就是下面这段代码

[html] view plain copy

  1. response.setContentType("application/json");
  2. response.setCharacterEncoding("UTF-8");
  3. request.setCharacterEncoding("UTF-8");
  4. /**
  5. * 接收json
  6. */
  7. BufferedReader reader = request.getReader();
  8. String json = reader.readLine();
  9. System.out.println(json);
  10. Gson gson =new Gson();
  11. User user = gson.fromJson(json, User.class);
  12. System.out.println(user.getUsername());
  13. System.out.println(user.getPassword());

然后就是服务器端的javabean

[html] view plain copy

  1. public class User {
  2. private String id;
  3. private String username;
  4. private String password;
  5. private String Nickname;
  6. private String Individuality_signature;
  7. public String getNickname() {
  8. return Nickname;
  9. }
  10. public void setNickname(String nickname) {
  11. Nickname = nickname;
  12. }
  13. public String getIndividuality_signature() {
  14. return Individuality_signature;
  15. }
  16. public void setIndividuality_signature(String individuality_signature) {
  17. Individuality_signature = individuality_signature;
  18. }
  19. public String getId() {
  20. return id;
  21. }
  22. public void setId(String id) {
  23. this.id = id;
  24. }
  25. public String getUsername() {
  26. return username;
  27. }
  28. public void setUsername(String username) {
  29. this.username = username;
  30. }
  31. public String getPassword() {
  32. return password;
  33. }
  34. public void setPassword(String password) {
  35. this.password = password;
  36. }
  37. }

到这里基本的过程就结束了,从安卓端上传json数据到服务器端解析json数据,将json数据解析成javabean对象。不知道对初学者有没有帮助,又不懂的可以直接@我,

安卓okhttp3与服务器通过json数据交互解析与上传

相关推荐