使用 retrofit2 android 实现请求
implementing a request using retrofit2 android
这是对邮递员的成功请求,图中显示了我试图在 retrofit2 中实现的所有请求部分
这是我尝试实现它的代码
public interface APIService {
@Multipart
@POST("upload_operator_data.php")
Call<ResponseBody> uploadImage(@Part MultipartBody.Part profile_image
, @Query("jwt") String jwt);
}
public class APIClient {
private static Retrofit retrofit;
public static Retrofit getClient(String url)
{
if(retrofit==null)
{
retrofit = new Retrofit.Builder().baseUrl(url).addConverterFactory(GsonConverterFactory.create()).build();
}
return retrofit;
}
}
public class APIUtils {
public static final String URL ="https://tsaw.tech/AppApi/Operator/";
public static APIService getService() {
return APIClient.getClient(URL).create(APIService.class);
}
}
请求如下:
RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), file);
MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
Call<ResponseBody> call = mService.uploadImage(fileToUpload, JWT);
Log.d(TAG, "The requestSent:" + call.request().body());
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Log.d(TAG, "Image upload on response message: " + response.message());
Log.d(TAG, "Image upload on response body: " + response.body());
Log.d(TAG, "Image upload on response string: " + response.toString());
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(profile_form.this, t.toString(), Toast.LENGTH_LONG).show();
Log.d(TAG, "Image upload on Failure: " + t.getMessage());
}
});
并且日志输出为
2020-07-16 23:12:58.401 13078-13078/com.example.tsaw D/profile_form: Image upload on response message: Unauthorized
2020-07-16 23:12:58.402 13078-13078/com.example.tsaw D/profile_form: Image upload on response body: null
2020-07-16 23:12:58.402 13078-13078/com.example.tsaw D/profile_form: Image upload on response string: Response{protocol=http/1.1, code=401, message=Unauthorized, url=https://tsaw.tech/AppApi/Operator/upload_operator_data.php?jwt=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9leGFtcGxlLm9yZyIsImF1ZCI6Imh0dHA6XC9cL2V4YW1wbGUuY29tIiwiaWF0IjoxMzU2OTk5NTI0LCJuYmYiOjEzNTcwMDAwMDAsImRhdGEiOnsOo2BZao}
我真的不明白为什么邮递员请求成功而这个retrofit2请求不成功。
这里是完整的 activity 更多细节:
package com.example.tsaw.javafile;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.FileUtils;
import android.provider.MediaStore;
import android.support.v4.content.CursorLoader;
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.ImageView;
import android.widget.Toast;
import com.example.tsaw.R;
import com.example.tsaw.javafile.API.APIService;
import com.example.tsaw.javafile.API.APIUtils;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.xml.transform.Result;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import static android.widget.Toast.LENGTH_LONG;
public class profile_form extends AppCompatActivity {
private static final String TAG = profile_form.class.getSimpleName();
private Bitmap bitmap;
int PICK_IMAGE_REQUEST = 1;
Button open_camera, Submit;
ImageView profile_pic;
String imagpath;
String JWT;
APIService mService;
File file;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_form);
open_camera = findViewById(R.id.Open_Camera);
profile_pic = findViewById(R.id.imageView4);
Submit = findViewById(R.id.upload);
mService = APIUtils.getService();
// final String image = getStringImage(bitmap);
SharedPreferences prefs = getSharedPreferences("Token", MODE_PRIVATE);
JWT = prefs.getString("Token", null);
open_camera.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showFileChooser();
}
});
System.out.println("Jwt" + JWT);
Submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
uploadImage();
}
});
}
private void uploadImage() {
final String Token = JWT.toString();
Log.d(TAG, "The current token: " + Token);
RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), file);
MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("profile_image", file.getName(), requestBody);
Call<ResponseBody> call = mService.uploadImage(fileToUpload, Token);
Log.d(TAG, "The requestSent:" + call.request().url());
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Log.d(TAG, "Image upload on response message: " + response.message());
Log.d(TAG, "Image upload on response body: " + response.body());
Log.d(TAG, "Image upload on response string: " + response.toString());
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(profile_form.this, t.toString(), Toast.LENGTH_LONG).show();
Log.d(TAG, "Image upload on Failure: " + t.getMessage());
}
});
}
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (data == null) {
Toast.makeText(this, "File not found ", LENGTH_LONG).show();
return;
}
try {
InputStream is = getContentResolver().openInputStream(data.getData());
Bitmap bitmap = BitmapFactory.decodeStream(is);
// Log.d(TAG, String.valueOf(bitmap));
profile_pic.setImageBitmap(bitmap);
file = createFileFromBitmap(this,bitmap,"profile_pic");
} catch (IOException e) {
e.printStackTrace();
}
Uri imageURI = data.getData();
Log.d(TAG, "Image selected successfully: " + imageURI.toString());
Log.d(TAG, "Image selected successfully: " + file);
}
}
public File createFileFromBitmap(Context context,Bitmap bitmap,String filename) throws IOException {
//create a file to write bitmap data
File f = new File(context.getCacheDir(), filename);
f.createNewFile();
//Convert bitmap to byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 1 /*ignored for PNG*/, bos);
byte[] bitmapdata = bos.toByteArray();
//write the bytes in file
FileOutputStream fos = new FileOutputStream(f);
fos.write(bitmapdata);
fos.flush();
fos.close();
return f;
}
}
通过将创建请求的代码更改为
解决了这个问题
HashMap<String, RequestBody> map = new HashMap<>();
map.put("jwt", toRequestBody(token));
RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpeg"),file);
MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("profile_image", file.getName(), requestBody);
Call<ResponseBody> call = mService.uploadImage(fileToUpload, map);
API 接口:
public interface APIService {
@Multipart
@POST("upload_operator_data.php")
Call<ResponseBody> uploadImage(@Part MultipartBody.Part profile_image
, @PartMap() Map<String, RequestBody> partMap);
}
这是对邮递员的成功请求,图中显示了我试图在 retrofit2 中实现的所有请求部分
public interface APIService {
@Multipart
@POST("upload_operator_data.php")
Call<ResponseBody> uploadImage(@Part MultipartBody.Part profile_image
, @Query("jwt") String jwt);
}
public class APIClient {
private static Retrofit retrofit;
public static Retrofit getClient(String url)
{
if(retrofit==null)
{
retrofit = new Retrofit.Builder().baseUrl(url).addConverterFactory(GsonConverterFactory.create()).build();
}
return retrofit;
}
}
public class APIUtils {
public static final String URL ="https://tsaw.tech/AppApi/Operator/";
public static APIService getService() {
return APIClient.getClient(URL).create(APIService.class);
}
}
请求如下:
RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), file);
MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
Call<ResponseBody> call = mService.uploadImage(fileToUpload, JWT);
Log.d(TAG, "The requestSent:" + call.request().body());
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Log.d(TAG, "Image upload on response message: " + response.message());
Log.d(TAG, "Image upload on response body: " + response.body());
Log.d(TAG, "Image upload on response string: " + response.toString());
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(profile_form.this, t.toString(), Toast.LENGTH_LONG).show();
Log.d(TAG, "Image upload on Failure: " + t.getMessage());
}
});
并且日志输出为
2020-07-16 23:12:58.401 13078-13078/com.example.tsaw D/profile_form: Image upload on response message: Unauthorized
2020-07-16 23:12:58.402 13078-13078/com.example.tsaw D/profile_form: Image upload on response body: null
2020-07-16 23:12:58.402 13078-13078/com.example.tsaw D/profile_form: Image upload on response string: Response{protocol=http/1.1, code=401, message=Unauthorized, url=https://tsaw.tech/AppApi/Operator/upload_operator_data.php?jwt=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9leGFtcGxlLm9yZyIsImF1ZCI6Imh0dHA6XC9cL2V4YW1wbGUuY29tIiwiaWF0IjoxMzU2OTk5NTI0LCJuYmYiOjEzNTcwMDAwMDAsImRhdGEiOnsOo2BZao}
我真的不明白为什么邮递员请求成功而这个retrofit2请求不成功。
这里是完整的 activity 更多细节:
package com.example.tsaw.javafile;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.FileUtils;
import android.provider.MediaStore;
import android.support.v4.content.CursorLoader;
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.ImageView;
import android.widget.Toast;
import com.example.tsaw.R;
import com.example.tsaw.javafile.API.APIService;
import com.example.tsaw.javafile.API.APIUtils;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.xml.transform.Result;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import static android.widget.Toast.LENGTH_LONG;
public class profile_form extends AppCompatActivity {
private static final String TAG = profile_form.class.getSimpleName();
private Bitmap bitmap;
int PICK_IMAGE_REQUEST = 1;
Button open_camera, Submit;
ImageView profile_pic;
String imagpath;
String JWT;
APIService mService;
File file;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile_form);
open_camera = findViewById(R.id.Open_Camera);
profile_pic = findViewById(R.id.imageView4);
Submit = findViewById(R.id.upload);
mService = APIUtils.getService();
// final String image = getStringImage(bitmap);
SharedPreferences prefs = getSharedPreferences("Token", MODE_PRIVATE);
JWT = prefs.getString("Token", null);
open_camera.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showFileChooser();
}
});
System.out.println("Jwt" + JWT);
Submit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
uploadImage();
}
});
}
private void uploadImage() {
final String Token = JWT.toString();
Log.d(TAG, "The current token: " + Token);
RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), file);
MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("profile_image", file.getName(), requestBody);
Call<ResponseBody> call = mService.uploadImage(fileToUpload, Token);
Log.d(TAG, "The requestSent:" + call.request().url());
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
Log.d(TAG, "Image upload on response message: " + response.message());
Log.d(TAG, "Image upload on response body: " + response.body());
Log.d(TAG, "Image upload on response string: " + response.toString());
}
@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(profile_form.this, t.toString(), Toast.LENGTH_LONG).show();
Log.d(TAG, "Image upload on Failure: " + t.getMessage());
}
});
}
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (data == null) {
Toast.makeText(this, "File not found ", LENGTH_LONG).show();
return;
}
try {
InputStream is = getContentResolver().openInputStream(data.getData());
Bitmap bitmap = BitmapFactory.decodeStream(is);
// Log.d(TAG, String.valueOf(bitmap));
profile_pic.setImageBitmap(bitmap);
file = createFileFromBitmap(this,bitmap,"profile_pic");
} catch (IOException e) {
e.printStackTrace();
}
Uri imageURI = data.getData();
Log.d(TAG, "Image selected successfully: " + imageURI.toString());
Log.d(TAG, "Image selected successfully: " + file);
}
}
public File createFileFromBitmap(Context context,Bitmap bitmap,String filename) throws IOException {
//create a file to write bitmap data
File f = new File(context.getCacheDir(), filename);
f.createNewFile();
//Convert bitmap to byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 1 /*ignored for PNG*/, bos);
byte[] bitmapdata = bos.toByteArray();
//write the bytes in file
FileOutputStream fos = new FileOutputStream(f);
fos.write(bitmapdata);
fos.flush();
fos.close();
return f;
}
}
通过将创建请求的代码更改为
解决了这个问题 HashMap<String, RequestBody> map = new HashMap<>();
map.put("jwt", toRequestBody(token));
RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpeg"),file);
MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("profile_image", file.getName(), requestBody);
Call<ResponseBody> call = mService.uploadImage(fileToUpload, map);
API 接口:
public interface APIService {
@Multipart
@POST("upload_operator_data.php")
Call<ResponseBody> uploadImage(@Part MultipartBody.Part profile_image
, @PartMap() Map<String, RequestBody> partMap);
}