retrofit使用
2016-04-25 本文已影响509人
stepyu
定义接口
package com.weedfs.client.yj.weedfsClient.Interface;
import com.weedfs.client.yj.weedfsClient.dto.Upload;
import retrofit.client.Response;
import retrofit.http.GET;
import retrofit.http.Multipart;
import retrofit.http.POST;
import retrofit.http.Part;
import retrofit.http.Path;
import retrofit.http.Query;
import retrofit.http.Streaming;
import retrofit.mime.TypedInput;
public interface DirectApiI {
@Multipart
@POST("/submit")
Upload upload(@Query("collection") String collection, @Query("replication") String replication,
@Part("file") TypedInput input);
@GET("/{fid}")
@Streaming
Response get(
@Path("fid") String id);
}
使用接口
package com.weedfs.client.yj.weedfsClient;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Paths;
import retrofit.RestAdapter;
import retrofit.client.Response;
import retrofit.mime.TypedFile;
import com.weedfs.client.yj.weedfsClient.Interface.DirectApiI;
import com.weedfs.client.yj.weedfsClient.dto.Upload;
/**
* Hello world!
*
*/
public class App {
public static void main(String[] args) {
DirectApiI dai = new RestAdapter.Builder().setEndpoint("http://10.0.40.59:9335").build()
.create(DirectApiI.class);
Upload upload = dai.upload(
"testClient",
"001",
new TypedFile("text/plain", Paths.get(
"/Users/weedfs-java/src/resource/hello2.txt").toFile()));
System.out.println(upload.getFid() + " " + upload.getFilename() + " " + upload.getFileUrl() + " "
+ upload.getSize());
Response rs = dai.get(upload.getFid());
String filename = "/Users/weedfs-java/src/resource/hello3.txt";
InputStream is = null;
FileOutputStream fos = null;
try {
fos = new FileOutputStream(filename);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
is = rs.getBody().in();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int ch = 0;
try {
while((ch=is.read()) != -1){
fos.write(ch);
}
} catch (IOException e1) {
e1.printStackTrace();
} finally{ //关闭输入流等(略)
try {
fos.close();
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(rs.getStatus());
}
}