当前位置:首页 » 文件管理 » retrofit20上传

retrofit20上传

发布时间: 2022-06-11 14:08:40

① 如何通过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,

[java] view plain
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 +
'}';
}

}
然后就来建立接口了,其内容如下:
[java] view plain
public interface PostRoute {
@Headers({"Content-Type: application/json","Accept: application/json"})//需要添加头
@POST("api/FlyRoute/Add")
Call<FlyRouteBean> postFlyRoute(@Body RequestBody route);//传入的参数为RequestBody
}
接下来就是提交数据的了:
[java] view plain
FlyRouteBean flyRouteBean=new FlyRouteBean();
flyRouteBean=initdata(flyRouteBean);//根据Bean类初始化一个需要提交的数据类
Gson gson=new Gson();
String route= gson.toJson(flyRouteBean);//通过Gson将Bean转化为Json字符串形式
[java] view plain
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());
}
});
需要添加的依赖:
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta3'

② retrofit 怎么设置长连接 文件类型

想实现这一目标其实很简单,随便打开一个文件夹,将查看方式改为大图标,然后打开文件夹选项,打开查看选项卡,点击应用到文件夹,就可以了,具体操作步骤如下: 1、随便打开一个文件夹,点击红色方框中的向下三角,更多选项, 将查看类型改为大图标; 2、“工具”下拉菜单,选择文件夹选项; 3、选择查看选项卡,点击应用到文件夹, 4、在弹出的提示框中选择“是(Y)”,然后打开另外一个文件夹,看看自己的目的是否已经达到。

③ retrofit文件上传怎么post

文件里面作如下配置:StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());

④ 为什么Retrofit以Mutipart上传参数时,String参数会多一对双引号

“@Part(“data”) String des”在Post请求中默认的Content-Type类型是“application/json”,这就说明我们在接口中不能再使用@Part注解了

@Multipart
@POST("userPhoto")
Observable<BaseHttpResult<String>> uploadMultipleTypeFile(@PartMap Map<String, RequestBody> params);

Map<String, RequestBody> bodyMap = new HashMap<>();
bodyMap.put("photo"; filename=""+file.getName(), RequestBody.create(MediaType.parse("image/png"),file));
bodyMap.put("userId", toRequestBody(userId));
bodyMap.put("serialNumber", toRequestBody(serialNumber));

public static RequestBody toRequestBody(String value) {

⑤ android retrofit上传二进制流 byte[] img

以下是图片上传方式:
接口写法:
Java code?
1
2
3

@Multipart
@POST("/user/addLicenseInfo")
void addLicenseInfo(@QueryMap Map<String, Object> options, @Part("file") TypedFile file, Callback<JsonElement> response);

实现写法:
Java code?
1
2
3
4
5

API api = mRegisterActivity.createAPI();
Map<String, Object> options = new HashMap<String, Object>();
options.put("mobile",photoNumber);
TypedFile typedImage = new TypedFile(getMIMEType(pictureFile), pictureFile);
api.addLicenseInfo(options,typedImage,new Callback<JsonEleme

⑥ retrofit可以上传大文件吗

1.单张图片的上传

?

1
2
3
4
5
6
7
8
9
10

/**
* 上传一张图片
* @param description
* @param imgs
* @return
*/
@Multipart
@POST("/upload")
Call<String> uploadImage(@Part("fileName") String description,
@Part("file\"; filename=\"image.png\"")RequestBody imgs);

2.多张图片的上传

?

1
2
3
4
5
6
7
8
9
10
11
12
13
14

/**
* 上传三张图片
* @param description
* @param imgs
* @param imgs1
* @param imgs3
* @return
*/
@Multipart
@POST("/upload")
Call<String> uploadImage(@Part("fileName") String description,
@Part("file\"; filename=\"image.png\"")RequestBody imgs,
@Part("file\"; filename=\"image.png\"")RequestBody imgs1,
@Part("file\"; filename=\"image.png\"")RequestBody imgs3);

注意:目前是提供传3张,要想多上传目前我发现的方法就是想要多传一张,就多增加一个参数
@Part("file\"; filename=\"image.png\"")RequestBody imgs,以此类推。
大家看到上面觉得写法很漏,但是用于能力有限,只能想到这样。用Java中的可变参数解决之后,就只能传一张。不能多张。

?

1
2
3
4

@Multipart
@POST("/upload")
Call<String> uploadImage(@Part("fileName") String description,
@Part("file\"; filename=\"image.png\"")RequestBody ...imgs);

调用:
Call<String> call = apiManager.uploadImage( m[0],requestBody1,requestBody2,null);
这样写看上去很是高端,不幸的是只能传一张
3.最后是实现胡过程
3.1创建FileUploadService接口
?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27

public interface FileUploadService {
/**
* 上传一张图片
* @param description
* @param imgs
* @return
*/
@Multipart
@POST("/upload")
Call<String> uploadImage(@Part("fileName") String description,
@Part("file\"; filename=\"image.png\"")RequestBody imgs);

/**
* 上传三张图片
* @param description
* @param imgs
* @param imgs1
* @param imgs3
* @return
*/
@Multipart
@POST("/upload")
Call<String> uploadImage(@Part("fileName") String description,
@Part("file\"; filename=\"image.png\"")RequestBody imgs,
@Part("file\"; filename=\"image.png\"")RequestBody imgs1,
@Part("file\"; filename=\"image.png\"")RequestBody imgs3);
}

3.2创建Retrofit对象
?

1
2
3
4
5
6
7

private static final Retrofit sRetrofit = new Retrofit .Builder()
.baseUrl(ENDPOINT)
.addConverterFactory(GsonConverterFactory.create())
// .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) // 使用RxJava作为回调适配器
.build();

private static final FileUploadService apiManager = sRetrofit.create(FileUploadService.class);

3.3调用上传的方法
?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

public static void upload(String path){

String descriptionString = "hello, this is description speaking";

String[] m = new String[2];
m[0]= "share.png";
m[1]= "Screenshot_20160128-140709.png";
File[] ssssss= new File[2];
File file1 = new File("/storage/emulated/0/sc/share.png");
File file = new File("/storage/emulated/0/Pictures/ScreenShots/Screenshot_20160128-140709.png");
ssssss[0]=file;
ssssss[0]=file1;
RequestBody requestBody[] = new RequestBody[3];
RequestBody requestBody1 =
RequestBody.create(MediaType.parse("multipart/form-data"), file);
RequestBody requestBody2 =
RequestBody.create(MediaType.parse("multipart/form-data"), file1);
requestBody[0]=requestBody1;
requestBody[1]=requestBody2;
Call<String> call = apiManager.uploadImage( m[0],requestBody1,requestBody2,null);
call.enqueue(new Callback<String>() {
@Override
public void onResponse(Response<String> response, Retrofit retrofit) {
Log.v("Upload", response.message());
Log.v("Upload", "success");
}

@Override
public void onFailure(Throwable t) {
Log.e("Upload", t.toString());
}
});

}

4.服务器段代码:
服务器用的是struts接收:

@Controller
public class GetToken extends ActionSupport {

/**
*
*/
private static final long serialVersionUID = 1L;
private File[] file;
private String[] fileName;
public File[] getFile() {
return file;
}
public void setFile(File[] file) {
this.file = file;
}
public String[] getFileName() {
return fileName;
}
public void setFileName(String[] fileName) {
this.fileName = fileName;
}

@Action("/upload")
public void login() {
System.out.println("------"+Arrays.toString(file));
System.out.println("------"+Arrays.toString(fileName));
}

}

⑦ android retrofit 上传进度requestbody writeto 为什么会调用两次

用Retrofit发送网络请求和解析json的实例Retrofit是Android的一个非常好用的开源HTTPRequest。现在介绍一下Retrofit是如何使用的。。。。首先是导入Retrofit包,dependencies{compilefileTree(dir:'libs',include:['*.jar'])compile

热点内容
安卓手机壁纸如何更换成动态壁纸 发布:2025-01-20 01:40:27 浏览:705
安卓微信签名在哪里修改 发布:2025-01-20 01:25:31 浏览:109
安卓电脑管家怎么恢复出厂设置 发布:2025-01-20 01:24:06 浏览:313
qt编译sqlite库 发布:2025-01-20 01:22:30 浏览:525
360摄像头存储设置 发布:2025-01-20 01:16:01 浏览:538
js防缓存 发布:2025-01-20 01:15:47 浏览:495
编程生日卡 发布:2025-01-20 01:15:14 浏览:206
android备忘录源码 发布:2025-01-20 01:06:32 浏览:455
怎么禁用aspx缓存 发布:2025-01-20 01:00:50 浏览:688
我的手机如何恢复安卓系统 发布:2025-01-20 00:55:48 浏览:367