android retrofit2 post/get方法上传文件到服务器

为了不因为小问题出错 上来第一步 先配置依赖 权限deng

 

    compile 'com.squareup.retrofit2:retrofit:2.0.1'
    compile 'com.squareup.retrofit2:converter-gson:2.0.1'
    compile 'com.squareup.retrofit2:adapter-rxjava:2.0.1'
    compile 'io.reactivex:rxandroid:1.1.0'
    compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
    compile 'com.squareup.okhttp3:logging-interceptor:3.4.1'
    compile 'com.google.code.gson:gson:2.8.2'

 

 

第二步就是对应的权限

 

 

 

  
    
    
    


第三步就是对应的代码   创建一个接口对应的事你们后台的接口 这种是对应的post 请求 对应的字段传到map 一个集合    @headers是对应的接口的请求头,有的接口需要有不需要 根据自己后台的需求

 

public interface ApiService {
   // http://wallasdet-apsai-tesasdat.launchaasdin.orgsad:500asd00/vsa1/addasdress/0xa2580adsadas8a4e3f54d2bcb529asdb99af8514e4d61f4651?page=0&limit=5
  // http://wallet-apiasda-test.launchainadass.org:50sad000/vdas1/addressads/0x53b3f2sa0e02368ba8d2af21d59d9edbeea52ec28asdasa?page=0&limit=5
   @Headers({"Content-Type:application/x-www-form-urlencoded",
           "Content-Length:59"})
   @FormUrlEncoded
   @POST("v1/ipfs")
   Observable getHomes(@FieldMap Map map);

}

 这里面 强调一点 我用的 mvp 框架 需要 创建 modol   view   presen 这三层 要是不懂就看我下面的效果图

android retrofit2 post/get方法上传文件到服务器_第1张图片
 


下一步 在model文件夹下创建  接口 IModel

public interface IModel {
    void getUrl(String url);
}

接下来对应的还是在这个文件夹里面创建 UserModel

public class UserModel implements IModel {
    News list;
    private OnFinish onFinish;

    public interface OnFinish {
        void OnFinishListener(News list);
    }

    public void setOnFinish(OnFinish onFinish) {
        this.onFinish = onFinish;
    }

    @Override
    public void getUrl(String url) {

        Map hah=new HashMap<>();
        hah.put("address","0x53b3f20e02368ba8d2af21d59d9edbeea52ec28a");
        hah.put("name","config_system_switchs.txt");
        hah.put("hash","111");
        Retrofit retrofit = new Retrofit.Builder().baseUrl(url).addConverterFactory(GsonConverterFactory.create()).addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build();
        ApiService apiService = retrofit.create(ApiService.class);
        Observable homes = apiService.getHomes(hah);
        homes.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())

                .subscribe(new Observer() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e("fsdfsdfsd", "onNext: "+e );

                    }

                    @Override
                    public void onNext(News news) {
                        Log.e("fsdfsdfsd", "onNext: "+news.getName() );
                        try {
                            savaFileToSD("wlb2.txt",news.getName());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        list = news;
                    }
                });
    }


    public void savaFileToSD(String filename, String filecontent) throws Exception {
        //如果手机已插入sd卡,且app具有读写sd卡的权限
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
          //  filename = Environment.getExternalStorageDirectory().getCanonicalPath() + "/" + filename;
            Log.e("fsdfsdfsd", "onNext: "+filename );
            //这里就不要用openFileOutput了,那个是往手机内存中写数据的
            FileOutputStream output = new FileOutputStream(filename);
            output.write(filecontent.getBytes());
            //将String字符串以字节流的形式写入到输出流中
            output.close();
            //关闭输出流
        }else  Log.e("fsdfsdfsd", "onNext: "+"SD卡不存在或者不可读写" );
    }
//https://blog.csdn.net/zadarrien_china/article/details/55226068
}

下面 是对应的 view层   在view文件夹下面创建 接口 

 

public interface IView {
    void getNews(News list);
}


接下来就是对应的P层 在对应创建P层的文件夹里面

public class Api {
    public static final String HOME_URL="http://wallsddfet-api-tesdfst.launchdfsain.org:50ds000/";
    // http://walfsdlet-api-tedsfst.lausfnchainfsd.org:5000df0/vfs1/addrsdfess/0xa25808a4e3f54d2bcb529b99afsdfs8514e4d61f4651?page=0&limit=5
}

对应的创建一个  UserPresenter

 
public class UserPresenter implements UserModel.OnFinish{
    private final IView userView;
    private final UserModel userModel;

    public UserPresenter(IView userView) {
        this.userView = userView;
        this.userModel = new UserModel();
        userModel.setOnFinish(this);
    }

    public void getUser(String url){
        userModel.getUrl(url);
    }



    @Override
    public void OnFinishListener(News list) {
        userView.getNews(list);
    }

}
 
 
对应的是一个后台数据的类型 我们全是Sting
 
public class News {


    /**
     * _id : 5acf4442ebc298000188e116
     * status : 1
     * created_at : 2018-04-12T11:34:26.549386431Z
     * updated_at : 2018-04-12T11:34:26.549386572Z
     * address : 0x53b3f20e02368ba8d2af21d59d9edbeea52ec28a
     * name : config_system_switchs.txt
     * hash : 45646
     */

    private String _id;
    private int status;
    private String created_at;
    private String updated_at;
    private String address;
    private String name;
    private String hash;

    public String get_id() {
        return _id;
    }

    public void set_id(String _id) {
        this._id = _id;
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public String getCreated_at() {
        return created_at;
    }

    public void setCreated_at(String created_at) {
        this.created_at = created_at;
    }

    public String getUpdated_at() {
        return updated_at;
    }

    public void setUpdated_at(String updated_at) {
        this.updated_at = updated_at;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getHash() {
        return hash;
    }

    public void setHash(String hash) {
        this.hash = hash;
    }
}


接下来就是主页面

 
public class MainActivity extends AppCompatActivity implements IView{

    UserPresenter userPresenter;
    TextView tv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv=findViewById(R.id.tv);
        userPresenter=new UserPresenter(this);
        userPresenter.getUser(Api.HOME_URL);

    }

    @Override
    public void getNews(News list) {
        tv.setText(list.getName());
    }
}

下面对应的是post请求 以

public interface ApiService {
    @FormUrlEncoded
    @POST("myFav?")
    Observable getHomes(@FieldMap Map map);

}

 

你可能感兴趣的:(android retrofit2 post/get方法上传文件到服务器)