我收到以下成功消息,但仍然在上次接收或接收到默认图片链接,当前所选图片未上传,api需要api令牌," _method": " PUT"和图片网址作为参数,任何帮助将不胜感激,代码列在下面谢谢。
此外,API是在php laravel上制作的,其中没有PUT方法,所以主要方法是POST但是" _method":" PUT"参数允许你上传图像,没有_method它变成一个POST消息和其他所有参数而不是必须的,请检查图像。
回复{protocol = http / 1.1,code = 200,message = OK,url = http://ec2-35-161-195-128.us-west-2.compute.amazonaws.com/api/account}
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
StringBuilder stringBuilder = new StringBuilder(AUTHORIZATION);
sharedPreferences = this.getSharedPreferences(getResources().getString(R.string.token), 0);
stringBuilder.append(sharedPreferences.getString(getResources().getString(R.string.token), ""));
try {
uploadImage(file, stringBuilder.toString());
} catch (IOException e) {
e.printStackTrace();
}
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
public void uploadImage(File file, String auth) throws IOException {
OkHttpClient client = new OkHttpClient();
/*RequestBody requestBody1 = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("_method", "PUT")
.build();
RequestBody requestBody2 = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("image", file.getName(), RequestBody.create(MEDIA_TYPE.parse("image"), file))
.build();
Request request = new Request.Builder()
.url("http://ec2-35-161-195-128.us-west-2.compute.amazonaws.com/api/account")
.addHeader("Authorization", auth)
.put(requestBody1)
.put(requestBody2)
.build();*/
RequestBody formBody1 = new FormBody.Builder()
.add("_method", "PUT")
.build();
RequestBody requestBody2 = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("image", file.getName(), RequestBody.create(MEDIA_TYPE.parse("image"), file))
.build();
Request request = new Request.Builder()
.url("http://ec2-35-161-195-128.us-west-2.compute.amazonaws.com/api/account")
.addHeader("Authorization", auth)
.put(formBody1)
.put(requestBody2)
.build();
client.newCall(request).enqueue(new okhttp3.Callback() {
@Override
public void onFailure(okhttp3.Call call, IOException e) {
Toast.makeText(DetailActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
@Override
public void onResponse(okhttp3.Call call, okhttp3.Response response) throws IOException {
response.body();
}
});
postman api image = https://i.imgur.com/AoCFZI6.png