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

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

通过安装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 ;
}
} @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'

源代码下载

Android 如何通过Retrofit提交Json格式数据的更多相关文章

  1. app开发历程————Android程序解析服务器端的JSON格式数据,显示在界面上

    上一篇文章写的是服务器端利用Servlet 返回JSON字符串,本文主要是利用android客户端访问服务器端链接,解析JSON格式数据,放到相应的位置上. 首先,android程序的布局文件main ...

  2. ajax 提交 json格式数据到后台

    例子:$.ajax({ type: 'POST', url: "/ROOT/modify.do", contentType: "application/json" ...

  3. Django day11(一) ajax 文件上传 提交json格式数据

    一: 什么是ajax? AJAX(Asynchronous Javascript And XML)翻译成中文就是“异步Javascript和XML”.即使用Javascript语言与服务器进行异步交互 ...

  4. 向Solr数据集提交Json格式数据(Scala,Post)

    import scalaj.http.Http class SolrAdd () {// 方法接受两个参数,dataType为数据集名称,jsonString为数据json字符串 def postTo ...

  5. jQuery动态添加元素,并提交json格式数据到后台

    参考:https://www.cnblogs.com/shj-com/p/7878727.html 下载 下载该插件的地址是:http://www.bootcdn.cn/jquery.serializ ...

  6. Android学习笔记_14_对JSON格式数据的处理

    public class ParseJsonTest extends AndroidTestCase{ public void testJson() throws Exception { String ...

  7. 使用基于Android网络通信的OkHttp库实现Get和Post方式简单操作服务器JSON格式数据

     目录 前言 1 Get方式和Post方式接口说明 2 OkHttp库简单介绍及环境配置 3 具体实现 前言 本文具体实现思路和大部分代码参考自<第一行代码>第2版,作者:郭霖:但是文中讲 ...

  8. 实现android上解析Json格式数据功能

    实现android上解析Json格式数据功能,该源码转载于安卓教程网的,http://android.662p.com ,个人感觉还不错的,大家可以看看一下吧. package com.practic ...

  9. Android读取JSON格式数据

    Android读取JSON格式数据 1. 何为JSON? JSON,全称为JavaScript Object Notation,意为JavaScript对象表示法. JSON 是轻量级的文本数据交换格 ...

随机推荐

  1. 三、Chrome开发者工具详解(3)-Timeline面板

    摘自: http://www.cnblogs.com/charliechu/p/5992177.html

  2. MVC 登录后重定向回最初请求的 URL FormsAuthentication.RedirectFromLoginPage

    在传统的Asp.net webForm 中如果使用 Form身份验证.登录后重定向到最初请求的页面只需使用 FormsAuthentication.RedirectFromLoginPage 但在MV ...

  3. 查看Spring源码的方法

    来自为知笔记(Wiz)

  4. linux内核中ip,tcp等头的定义(转)

    一.MAC帧头定义 /*数据帧定义,头14个字节,尾4个字节*/typedef struct _MAC_FRAME_HEADER{ char m_cDstMacAddress[6];    //目的m ...

  5. 利用python数据分析panda学习笔记之基本功能

    1 重新生成索引 如果某个索引值不存在就引入缺失值 from pandas import Series,DataFrame import pandas as pd import numpy as np ...

  6. sed的基础用法简介

    sed 最近学习了一些sed的相关知识,初步接触sed以后给我的感受主要有两点.首先是sed强大的功能,学了以后发现之前写的脚本利用sed以后会简化很多啊,具体的有些利用sed编辑shell脚本的思路 ...

  7. Makefile研究 (一)—— 必备语法

    摘自:http://blog.csdn.net/jundic/article/details/17535445 参考文档:http://blog.csdn.net/wrx1721267632/arti ...

  8. C#实现简易ajax调用后台方法

    在当前WEB当中,有些人都会抛弃asp.net的服务器控件,转而使用ajax来进行数据的交互和存储. 当我们大量使用ajax的时候,对于新手而言,肯定会创建很多的ashx或aspx页面,通过拼接参数, ...

  9. sqlserver——视图

    数据库中的视图是一个虚拟表.同真实的表一样,视图包含一系列带有名称的列和行数据,行和列数据用来自由定义视图和查询所引用的表,并且在引用视图时动态产生.本篇将通过一些实例来介绍视图的概念,视图的作用,创 ...

  10. 前端之CSS2

    CSS盒子模型 CSS盒子模型介绍 盒子模型解释 元素在页面中显示成一个方块,类似一个盒子,CSS盒子模型就是使用现实中盒子来做比喻,帮助我们设置元素对应的样式. 盒子模型示意图如下: 把元素叫做盒子 ...