使用Retrofits2上传文件到android中的服务器

时间:2018-05-15 08:35:20

标签: android server retrofit2

为什么我不能将文件上传到服务器?当我使用Log.d打印到日志屏幕时,它报告错误无法连接到192.168.10.2:8080虽然我已经要求获得Internet的许可并读取设备的内部存储器。

APIUtils.java

import android.provider.ContactsContract;

public class APIUtils {
    public static final String Base_Url = "http://192.168.10.2:8080/Quanlysinhvien/";

    public static DataClient getData(){

        return RetrofitClient.getClient(Base_Url).create(DataClient.class);
    }
}

DataClient.java

import okhttp3.MultipartBody;
import retrofit2.Call;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;

public interface DataClient {

    @Multipart
    @POST("uploadhinhanh.php")
    Call<String> UploadPhot(@Part MultipartBody.Part phto);
    }

RetrofitClient.java

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitClient {
    private static Retrofit retrofit = null;
    public static Retrofit getClient(String baseurl){
        OkHttpClient builder = new OkHttpClient.Builder()
                .readTimeout(5000, TimeUnit.MILLISECONDS)
                .writeTimeout(5000, TimeUnit.MILLISECONDS)
                .connectTimeout(10000, TimeUnit.MILLISECONDS)
                .retryOnConnectionFailure(true)
                .build();
        Gson gson = new GsonBuilder().setLenient().create();
        retrofit = new Retrofit.Builder()
                .baseUrl(baseurl)
                .client(builder)
                .addConverterFactory(GsonConverterFactory.create())
        .build();
        return retrofit;

    }
}

DangKyActivity.java

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.example.nhutkhanh.demoretrofit2.Retrofit2.APIUtils;
import com.example.nhutkhanh.demoretrofit2.Retrofit2.DataClient;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Callback;
import retrofit2.Response;

public class DangKyActivity extends AppCompatActivity {

    ImageView imgdangky;
    EditText edtUsername, edtPassword;
    Button btnhuy, btnxacnhan;
    int Request_Code_Image = 123;
    String realpath = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dang_ky);
        anhxa();
        imgdangky.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_PICK);
                intent.setType("image/*");
                startActivityForResult(intent, Request_Code_Image);
            }
        });
        btnxacnhan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                File file = new File(realpath);
                String file_path = file.getAbsolutePath();
                String[] mangtenfile = file_path.split("\\.");

                file_path = mangtenfile[0] + System.currentTimeMillis() + "." + mangtenfile[1];
                RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/from-data"), file);

                MultipartBody.Part body = MultipartBody.Part.createFormData("uploaded_file", file_path, requestBody);

                DataClient dataClient = APIUtils.getData();
                retrofit2.Call<String> callback = dataClient.UploadPhot(body);
                callback.enqueue(new Callback<String>() {
                    @Override
                    public void onResponse(retrofit2.Call<String> call, Response<String> response) {
                        if(response != null){
                            String message = response.body();
                            Log.d("AAA", message);
                        }
                    }

                    @Override
                    public void onFailure(retrofit2.Call<String> call, Throwable t) {
                        Log.d("BBB", "Lỗi " + t.getMessage());
                    }
                });
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == Request_Code_Image && resultCode == RESULT_OK && data != null){
            Uri uri = data.getData();
            realpath = getRealPathFromURI(uri);
            try {
                InputStream inputStream = getContentResolver().openInputStream(uri);
                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                imgdangky.setImageBitmap(bitmap);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
    public String getRealPathFromURI (Uri contentUri) {
        String path = null;
        String[] proj = { MediaStore.MediaColumns.DATA };
        Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
        if (cursor.moveToFirst()) {
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
            path = cursor.getString(column_index);
        }
        cursor.close();
        return path;
    }
    private void anhxa() {
        imgdangky = (ImageView)findViewById(R.id.imageViewDK);
        edtPassword = (EditText)findViewById(R.id.editTextDKMK);
        edtUsername = (EditText)findViewById(R.id.editTextDKTK);
        btnhuy = (Button)findViewById(R.id.buttonHuy);
        btnxacnhan = (Button)findViewById(R.id.buttonXacNhan);
    }
}

MainActivity.java

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}

0 个答案:

没有答案