如何使用改造发送请求字符串参数。我已经提交了下面的代码。这里如何添加字符串参数并发送到服务器。
应用配置:
公共类AppConfig{
public static String BASE_URL = "http://104.239.173.64/peoplecaddie-api";
public static Retrofit getRetrofit() {
return new Retrofit.Builder()
.baseUrl(AppConfig.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
ApiConfig:
public interface ApiConfig {
@Multipart
@POST("/general/Candidate/fileUpload")
Call<ServerResponse> upload(
@Header("Authorization") String authorization,
@PartMap Map<String, RequestBody> map
);
}
服务器响应:
public class ServerResponse {
// variable name should be same as in the json response from php
@SerializedName("success")
boolean success;
@SerializedName("message")
String message;
public String getMessage() {
return message;
}
public boolean getSuccess() {
return success;
}
}
public class MainActivity extends AppCompatActivity {
Button btnUpload, btnPickImage, btnPickVideo;
String mediaPath;
ImageView imgView;
String[] mediaColumns = {MediaStore.Video.Media._ID};
ProgressDialog progressDialog;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Uploading...");
btnUpload = (Button) findViewById(R.id.upload);
btnPickImage = (Button) findViewById(R.id.pick_img);
btnPickVideo = (Button) findViewById(R.id.pick_vdo);
imgView = (ImageView) findViewById(R.id.preview);
btnUpload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
uploadFile();
}
});
btnPickImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, 0);
}
});
// Video must be low in Memory or need to be compressed before uploading...
btnPickVideo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, 1);
}
});
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client2 = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
// When an Image is picked
if (requestCode == 0 && resultCode == RESULT_OK && null != data) {
// Get the Image from data
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
assert cursor != null;
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
mediaPath = cursor.getString(columnIndex);
// Set the Image in ImageView for Previewing the Media
imgView.setImageBitmap(BitmapFactory.decodeFile(mediaPath));
cursor.close();
} // When an Video is picked
else if (requestCode == 1 && resultCode == RESULT_OK && null != data) {
// Get the Video from data
Uri selectedVideo = data.getData();
String[] filePathColumn = {MediaStore.Video.Media.DATA};
Cursor cursor = getContentResolver().query(selectedVideo, filePathColumn, null, null, null);
assert cursor != null;
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
mediaPath = cursor.getString(columnIndex);
// Set the Video Thumb in ImageView Previewing the Media
imgView.setImageBitmap(getThumbnailPathForLocalFile(MainActivity.this, selectedVideo));
cursor.close();
} else {
Toast.makeText(this, "You haven't picked Image/Video", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG).show();
}
}
// Providing Thumbnail For Selected Image
public Bitmap getThumbnailPathForLocalFile(Activity context, Uri fileUri) {
long fileId = getFileId(context, fileUri);
return MediaStore.Video.Thumbnails.getThumbnail(context.getContentResolver(),
fileId, MediaStore.Video.Thumbnails.MICRO_KIND, null);
}
// Getting Selected File ID
public long getFileId(Activity context, Uri fileUri) {
Cursor cursor = context.managedQuery(fileUri, mediaColumns, null, null, null);
if (cursor.moveToFirst()) {
int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID);
return cursor.getInt(columnIndex);
}
return 0;
}
// Uploading Image/Video
private void uploadFile() {
progressDialog.show();
// Map is used to multipart the file using okhttp3.RequestBody
Map<String, RequestBody> map = new HashMap<>();
File file = new File(mediaPath);
RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), file);
map.put("fileContent0\"; filename=\"" + file.getName() + "\"", requestBody);
ApiConfig getResponse = AppConfig.getRetrofit().create(ApiConfig.class);
Call<ServerResponse> call = getResponse.upload(token, map);
call.enqueue(new Callback<ServerResponse>() {
@Override
public void onResponse(Call<ServerResponse> call, Response<ServerResponse> response) {
ServerResponse serverResponse = response.body();
if (serverResponse != null) {
if (serverResponse.getSuccess()) {
Log.e("Response", serverResponse.getMessage());
Toast.makeText(getApplicationContext(), serverResponse.getMessage(), Toast.LENGTH_SHORT).show();
} else {
Log.e("Response", serverResponse.getMessage());
Toast.makeText(getApplicationContext(), serverResponse.getMessage(), Toast.LENGTH_SHORT).show();
}
} else {
Log.v("Response", serverResponse.toString());
}
progressDialog.dismiss();
}
@Override
public void onFailure(Call<ServerResponse> call, Throwable t) {
Log.e("Throwable", t.toString());
}
});
}
@Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client2.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app URL is correct.
Uri.parse("android-app://com.delaroystudios.androidupload/http/host/path")
);
AppIndex.AppIndexApi.start(client2, viewAction);
}
@Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
Action viewAction = Action.newAction(
Action.TYPE_VIEW, // TODO: choose an action type.
"Main Page", // TODO: Define a title for the content shown.
// TODO: If you have web page content that matches this app activity's content,
// make sure this auto-generated web page URL is correct.
// Otherwise, set the URL to null.
Uri.parse("http://host/path"),
// TODO: Make sure this auto-generated app URL is correct.
Uri.parse("android-app://com.delaroystudios.androidupload/http/host/path")
);
AppIndex.AppIndexApi.end(client2, viewAction);
client2.disconnect();
}
}
在上面的示例中,代码只是在请求主体的帮助下传递了令牌和文件。
这就是如何使用改型将下面的登录参数详细信息作为请求参数发送。当我尝试时,我得到了/Throwable:com.google.格森。流动格式错误的JSONException:使用JsonReader。setLenient(true)在第1行第1列路径$处接受格式错误的JSON。这是个例外。
HashMap<String, String> login_params = new HashMap<String, String>();
login_params.put("fileCount", "1");
login_params.put("id","1743");
login_params.put("fileType", "SAMPLE");
login_params.put("platform", "Android");
login_params.put("externalID", "portpolio");
您可以使用@PartMap annotation在文件请求中传递参数。PartMap是“Key”和RequestBody的映射。因此,首先,您必须创建要传递的参数的RequestBody对象,然后创建该参数的Map对象,并将其作为参数传递。
例如,你在api接口中的方法是,
@Multipart
@POST("upload")
Call<ResponseBody> uploadFileWithPartMap(
@PartMap() Map<String, RequestBody> partMap,
@Part MultipartBody.Part file);
请求是,
MultipartBody.Part body = prepareFilePart("photo", fileUri);
// create a map of data to pass along
RequestBody token= RequestBody.create(
MediaType.parse(MULTIPART_FORM_DATA), "token_string");
HashMap<String, RequestBody> map = new HashMap<>();
map.put("token", token);
-----------------
private MultipartBody.Part prepareFilePart(String partName, Uri fileUri) {
// https://github.com/iPaulPro/aFileChooser/blob/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java
// use the FileUtils to get the actual file by uri
File file = FileUtils.getFile(this, fileUri);
// create RequestBody instance from file
RequestBody requestFile =
RequestBody.create(MediaType.parse(MULTIPART_FORM_DATA), file);
// MultipartBody.Part is used to send also the actual file name
return MultipartBody.Part.createFormData(partName, file.getName(), requestFile);
}
最后,调用方法是,
// finally, execute the request
Call<ResponseBody> call = service.uploadFileWithPartMap(map, body);
call.enqueue(...);
我希望这将有助于你和详细的参考,请查看此链接https://futurestud.io/tutorials/retrofit-2-passing-multiple-parts-along-a-file-with-partmap
我正在使用以下接受多个文件的FastAPIendpoint: 我想先输入参数,然后输入列表,但我找不到执行有效 post 请求的方法: 如果我只上传作为元组工作列表,但我不知道如何传入参数。
我可以使用将文件上载为 上面的代码运行良好。 现在,我想对同一作业使用。我试着在网上搜索并实现代码。但我无法得到结果。 html代码如下所示: 代码中没有任何形式。如何解决问题?
问题内容: 如果我执行以下操作: 我得到: 显然,cStringIO.StringIO对象没有足够接近库中的子程序来适应subprocess.Popen。我该如何解决? 问题答案: 说明文件: 请注意,如果要将数据发送到进程的stdin,则需要使用创建Popen对象。同样,要在结果元组中获得除None以外的任何内容,你还需要提供和/或。 替换 警告使用而不是,或来避免死锁,因为任何其他OS管道缓冲
问题内容: 我应该如何在jQuery Ajax请求中传递查询字符串值?我目前按照以下方式进行操作,但是我敢肯定有一种更清洁的方法,不需要我手动编码。 我已经看到了将查询字符串参数作为数组传递的示例,但是我看到的这些示例没有使用模型,而是直接使用。例如: 我更喜欢使用$ .ajax()格式,因为这是我习惯的格式(没有特别好的理由-只是个人喜好)。 编辑09/04/2013: 在我的问题结束(如“太过
我应该如何在jQuery Ajax请求中传递查询字符串值?我目前是这样做的,但我肯定有一个更干净的方法,不需要我手动编码。 我见过查询字符串参数作为数组传递的示例,但这些示例没有使用模型,而是直接使用。例如: 我更喜欢使用$.ajax()格式,因为这是我习惯的格式(没有特别好的理由--只是个人偏好)。 编辑09/04/2013: 在我的问题结束后(因为“太本地化”),我发现了一个相关的(相同的)问
问题内容: 我正在创建一个简单的登录页面,我想将登录名和密码参数作为UTF-8编码的字符串传递。正如您在下面的代码中看到的那样,第一行是我将编码设置为UTF-8的位置,但这似乎毫无意义,因为它不起作用。当我在重音符号中使用登录名和密码参数时,结果页面会收到奇怪的字符。 如何以一种适用于所有浏览器的方式正确设置字符编码? 问题答案: 在只设置响应的字符编码和所述HTTP的属性标题中。基本上,它告诉服