Android如何通过Retrofit提交Json格式数据

本文将介绍如何通过retrofit库post一串json格式的数据。首先post的json数据格式如下:

{
 "Id": "string",
 "DeviceId": "string",
 "Name": "string",
 "SumDistance": 0,
 "RouteNo": "string",
 "SumPoints": 0,
 "SetupTime": "2016-06-10T13:11:00.766Z",
 "UsedTime": 0,
 "Points": [
  {
   "Id": "string",
   "RouteNo": "string",
   "Name": "string",
   "Longitude": "string",
   "Latitude": "string",
   "Height": 0,
   "Distance": 0,
   "Yaw": 0,
   "Pitch": 0,
   "Speed": 0,
   "Usedtime": 0
  }
 ]
}

通过安装Android studio gsonformat插件,根据上面的json格式自动生成一个Bean类,本文命名为FlyRouteBean,

package com.example.administrator.retrofitex; 
import java.util.List; 
 
import android.os.Parcel; 
import android.os.Parcelable; 
 
/** 
 * Created by Administrator on 2016/6/10. 
 */ 
public class FlyRouteBean{ 
 
  /** 
   * Id : string 
   * DeviceId : string 
   * Name : string 
   * SumDistance : 0 
   * RouteNo : string 
   * SumPoints : 0 
   * SetupTime : 2016-05-23T06:20:50.254Z 
   * UsedTime : 0 
   * Points : [{"Id":"string","RouteNo":"string","Name":"string","Longitude":"string","Latitude":"string","Height":0,"Distance":0,"Yaw":0,"Pitch":0,"Speed":0,"Usedtime":0}] 
   */ 
 
  public String Id; 
  public String DeviceId; 
  public String Name; 
  public double SumDistance; 
  public String RouteNo; 
  public int SumPoints; 
  public String SetupTime; 
  public double UsedTime; 
  /** 
   * Id : string 
   * RouteNo : string 
   * Name : string 
   * Longitude : string 
   * Latitude : string 
   * Height : 0 
   * Distance : 0 
   * Yaw : 0 
   * Pitch : 0 
   * Speed : 0 
   * Usedtime : 0 
   */ 
 
  public List<PointsBean> Points; 
 
  public String getId() { 
    return Id; 
  } 
 
  public void setId(String Id) { 
    this.Id = Id; 
  } 
 
  public String getDeviceId() { 
    return DeviceId; 
  } 
 
  public void setDeviceId(String DeviceId) { 
    this.DeviceId = DeviceId; 
  } 
 
  public String getName() { 
    return Name; 
  } 
 
  public void setName(String Name) { 
    this.Name = Name; 
  } 
 
  public double getSumDistance() { 
    return SumDistance; 
  } 
 
  public void setSumDistance(double SumDistance) { 
    this.SumDistance = SumDistance; 
  } 
 
  public String getRouteNo() { 
    return RouteNo; 
  } 
 
  public void setRouteNo(String RouteNo) { 
    this.RouteNo = RouteNo; 
  } 
 
  public int getSumPoints() { 
    return SumPoints; 
  } 
 
  public void setSumPoints(int SumPoints) { 
    this.SumPoints = SumPoints; 
  } 
 
  public String getSetupTime() { 
    return SetupTime; 
  } 
 
  public void setSetupTime(String SetupTime) { 
    this.SetupTime = SetupTime; 
  } 
 
  public double getUsedTime() { 
    return UsedTime; 
  } 
 
  public void setUsedTime(double UsedTime) { 
    this.UsedTime = UsedTime; 
  } 
 
  public List<PointsBean> getPoints() { 
    return Points; 
  } 
 
  public void setPoints(List<PointsBean> Points) { 
    this.Points = Points; 
  } 
 
  public static class PointsBean implements Parcelable { 
    public String Id; 
    public String RouteNo; 
    public String Name; 
    public String Longitude; 
    public String Latitude; 
    public double Height; 
    public double Distance; 
    public double Yaw; 
    public double Pitch; 
    public double Speed; 
    public double Usedtime; 
 
    public String getId() { 
      return Id; 
    } 
 
    public void setId(String Id) { 
      this.Id = Id; 
    } 
 
    public String getRouteNo() { 
      return RouteNo; 
    } 
 
    public void setRouteNo(String RouteNo) { 
      this.RouteNo = RouteNo; 
    } 
 
    public String getName() { 
      return Name; 
    } 
 
    public void setName(String Name) { 
      this.Name = Name; 
    } 
 
    public String getLongitude() { 
      return Longitude; 
    } 
 
    public void setLongitude(String Longitude) { 
      this.Longitude = Longitude; 
    } 
 
    public String getLatitude() { 
      return Latitude; 
    } 
 
    public void setLatitude(String Latitude) { 
      this.Latitude = Latitude; 
    } 
 
    public double getHeight() { 
      return Height; 
    } 
 
    public void setHeight(double Height) { 
      this.Height = Height; 
    } 
 
    public double getDistance() { 
      return Distance; 
    } 
 
    public void setDistance(double Distance) { 
      this.Distance = Distance; 
    } 
 
    public double getYaw() { 
      return Yaw; 
    } 
 
    public void setYaw(double Yaw) { 
      this.Yaw = Yaw; 
    } 
 
    public double getPitch() { 
      return Pitch; 
    } 
 
    public void setPitch(double Pitch) { 
      this.Pitch = Pitch; 
    } 
 
    public double getSpeed() { 
      return Speed; 
    } 
 
    public void setSpeed(double Speed) { 
      this.Speed = Speed; 
    } 
 
    public double getUsedtime() { 
      return Usedtime; 
    } 
 
    public void setUsedtime(double Usedtime) { 
      this.Usedtime = Usedtime; 
    } 
 
    @Override 
    public String toString() { 
      return "PointsBean{" + 
          "Id='" + Id + '\'' + 
          ", RouteNo='" + RouteNo + '\'' + 
          ", Name='" + Name + '\'' + 
          ", Longitude='" + Longitude + '\'' + 
          ", Latitude='" + Latitude + '\'' + 
          ", Height=" + Height + 
          ", Distance=" + Distance + 
          ", Yaw=" + Yaw + 
          ", Pitch=" + Pitch + 
          ", Speed=" + Speed + 
          ", Usedtime=" + Usedtime + 
          '}'; 
    } 
 
    @Override 
    public void writeToParcel(Parcel dest, int flags) { 
      // TODO Auto-generated method stub 
      dest.writeString(Id); 
      dest.writeString(RouteNo); 
      dest.writeString(Name); 
      dest.writeString(Longitude); 
      dest.writeString(Latitude); 
      dest.writeDouble(Height);     
      dest.writeDouble(Distance); 
      dest.writeDouble(Yaw); 
      dest.writeDouble(Pitch); 
      dest.writeDouble(Speed); 
      dest.writeDouble(Usedtime);    
    } 
    public static final Creator<PointsBean> CREATOR=new Creator<PointsBean>() { 
 
      @Override 
      public PointsBean createFromParcel(Parcel source) { 
        // TODO Auto-generated method stub 
        PointsBean pointsBean=new PointsBean(); 
        pointsBean.setId(source.readString()); 
        pointsBean.setRouteNo(source.readString()); 
        pointsBean.setName(source.readString()); 
        pointsBean.setLongitude(source.readString()); 
        pointsBean.setLatitude(source.readString()); 
        pointsBean.setHeight(source.readInt()); 
        pointsBean.setDistance(source.readInt()); 
        pointsBean.setYaw(source.readInt()); 
        pointsBean.setPitch(source.readInt()); 
        pointsBean.setSpeed(source.readInt()); 
        pointsBean.setUsedtime(source.readInt()); 
        return pointsBean; 
      } 
 
      @Override 
      public PointsBean[] newArray(int size) { 
        // TODO Auto-generated method stub 
        return new PointsBean[size]; 
      } 
       
    }; 
 
    @Override 
    public int describeContents() { 
      // TODO Auto-generated method stub 
      return 0; 
    } 
  } 
 
  @Override 
  public String toString() { 
    return "FlyRouteBean{" + 
        "Id='" + Id + '\'' + 
        ", DeviceId='" + DeviceId + '\'' + 
        ", Name='" + Name + '\'' + 
        ", SumDistance=" + SumDistance + 
        ", RouteNo='" + RouteNo + '\'' + 
        ", SumPoints=" + SumPoints + 
        ", SetupTime='" + SetupTime + '\'' + 
        ", UsedTime=" + UsedTime + 
        ", Points=" + Points + 
        '}'; 
  } 
 
   
} 

然后就来建立接口了,其内容如下:

public interface PostRoute { 
  @Headers({"Content-Type: application/json","Accept: application/json"})//需要添加头 
  @POST("api/FlyRoute/Add") 
  Call<FlyRouteBean> postFlyRoute(@Body RequestBody route);//传入的参数为RequestBody 
} 

接下来就是提交数据的了:

FlyRouteBean flyRouteBean=new FlyRouteBean(); 
flyRouteBean=initdata(flyRouteBean);//根据Bean类初始化一个需要提交的数据类 
Gson gson=new Gson(); 
String route= gson.toJson(flyRouteBean);//通过Gson将Bean转化为Json字符串形式 
 Retrofit retrofit=new Retrofit.Builder() 
      .baseUrl(URL) 
      .addConverterFactory( GsonConverterFactory.create()) 
      .build(); 
  PostRoute postRoute=retrofit.create(PostRoute.class); 
  RequestBody body=RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),route); 
  Call<FlyRouteBean> call=postRoute.postFlyRoute(body); 
  call.enqueue(new Callback<FlyRouteBean>() { 
  @Override 
  public void onResponse(Call<FlyRouteBean> call, Response<FlyRouteBean> response) { 
    Log.e("sssss","-----------------------"+response.body().getDeviceId());//这里是用于测试,服务器返回的数据就是提交的数据。 
  } 
 
  @Override 
  public void onFailure(Call<FlyRouteBean> call, Throwable t) { 
    Log.e("sssss",t.getMessage()); 
  } 
}); 

<----------- 更新如何同时提交json数据和其他查询字段:--------------->

服务器端(ASP):核心代码如下,接收一个json格式学生类,加一个bool类型

 [HttpPost]
  public IHttpActionResult Info(Student stu, bool IsGay)
    {
      
      return Ok(stu.Name);
    }

客户端:

//接口地址:http://172.20.69.209:9665/api/Test/Info?IsGay={IsGay}
@POST("api/Test/Info")
Call<ResponseBody> postStudent(@Body RequestBody stu,@Query("IsGay") boolean IsGay);

实现代码:

Student stu=new Student();
stu.setId("20103177");
stu.setName("zpm");
stu.setAge(18);
Gson gson=new Gson();
String route= gson.toJson(stu);
Log.e("post", "//");

Retrofit retrofit=new Retrofit.Builder()
    .baseUrl("http://172.20.69.209:9665/")
    .addConverterFactory( GsonConverterFactory.create())
    .build();
PostRoute postRoute=retrofit.create(PostRoute.class);
RequestBody body=RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),route);
Call<ResponseBody> call=postRoute.postStudent(body,true);
call.enqueue(new Callback<ResponseBody>() {
  @Override
  public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
    try {
      Log.i("onResponse", response.body().string());
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  @Override
  public void onFailure(Call<ResponseBody> call, Throwable t) {
    Log.e("onFailure", t.getMessage());
  }
});

Log.e("postjson", route);

结果:

具体代码已经传到github

PS:本文中服务器都是楼主在局域网搭建的,

需要添加的依赖:

compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta3'

源代码下载

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持呐喊教程。

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。