retrofit20上傳
① 如何通過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