我已在某些库中找到了一些代码,我想知道如何添加自定义标题
来自选项。它应该从JS到本机(Java)接收一些东西。 我不是Java方面的专家。任何帮助将不胜感激。
这是它来自的存储库。 https://github.com/tranquangvu/react-native-uploader/
...
@ReactMethod
public void upload(ReadableMap options, Callback complete) {
final Callback completeCallback = complete;
try {
MultipartBody.Builder mRequestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM);
ReadableArray files = options.getArray("files");
String url = options.getString("url");
String method = options.getString("method");
if(options.hasKey("params")){
ReadableMap data = options.getMap("params");
ReadableMapKeySetIterator iterator = data.keySetIterator();
while(iterator.hasNextKey()){
String key = iterator.nextKey();
if(ReadableType.String.equals(data.getType(key))) {
mRequestBody.addFormDataPart(key, data.getString(key));
}
}
}
if(files.size() != 0){
for(int fileIndex=0 ; fileIndex<files.size(); fileIndex++){
ReadableMap file = files.getMap(fileIndex);
String uri = file.getString("filepath");
Uri file_uri;
if(uri.substring(0,10).equals("content://") ){
file_uri = Uri.parse(convertMediaUriToPath(Uri.parse(uri)));
}
else{
file_uri = Uri.parse(uri);
}
File imageFile = new File(file_uri.getPath());
if(imageFile == null){
Log.d(TAG, "FILE NOT FOUND");
completeCallback.invoke("FILE NOT FOUND", null);
return;
}
String mimeType = "image/png";
if(file.hasKey("filetype")){
mimeType = file.getString("filetype");
}
MediaType mediaType = MediaType.parse(mimeType);
String fileName = file.getString("filename");
String name = fileName;
if(file.hasKey("name")){
name = file.getString("name");
}
mRequestBody.addFormDataPart(name, fileName, RequestBody.create(mediaType, imageFile));
}
}
MultipartBody requestBody = mRequestBody.build();
Request request;
// NOTE: The author seems added the header statically, I wonder how can I add a custom header.
if(method.equals("PUT")) {
request = new Request.Builder()
.header("Accept", "application/json")
.url(url)
.put(requestBody)
.build();
}
else{
request = new Request.Builder()
.header("Accept", "application/json")
.url(url)
.post(requestBody)
.build();
}
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) {
Log.d(TAG, "Unexpected code" + response);
completeCallback.invoke(response, null);
return;
}
completeCallback.invoke(null, response.body().string());
} catch(Exception e) {
Log.d(TAG, e.toString());
}
}
答案 0 :(得分:1)
只需指示okhttp.Request.Builder
再插入一个标题:
request = new Request.Builder()
.header("Accept", "application/json")
.header("X-example-header", "example-value")
.url(url)
.put(requestBody)
.build();
编辑(例如,专门针对那些拒绝自己阅读文档的人):
或者使用类似的东西:
Request.Builder builder = new Request.Builder()
.header("Accept", "application/json");
for(int i = 0; i < 10; i++) {
builder.header("X-example-header-" + i, "example-value-" + i)
}
request = builder
.url(url)
.put(requestBody)
.build();