我试图使用来自我的android应用程序的PUT请求将一个文件上传到Amazon s3。我有一个从服务器与私人密钥暴露在同一个链接。
当尝试从POSTMAN上传文件时,它的工作原理是使用二元期权和内容类型应用程序/八位字节流或头中的应用程序/x-wan-form-urlencoded(两者都尝试过)上传文件,但如果使用表单数据上传相同的图像,它就不起作用。
在我的Android应用程序中,我已经尝试了使用排球的JsonObject请求,我正在得到。
Json组织异常
请在下面找到我的请求
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.PUT,
url, new JSONObject(parameters),
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
if (listener != null) {
Log.e("Response", response + "");
listener.onResult(response + "", responseCode);
if (showDialog == true) {
try {
mOverlayDialog.dismiss();
} catch (Exception e) {
// Crashlytics.logException(e);
}
try {
materialDialog.dismiss(); // To hide the progress bar
} catch (Exception e) {
// Crashlytics.logException(e);
}
}
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
if (listener != null) {
try {
if(error.networkResponse!=null && error.networkResponse.data!=null) {
String responseBody = new String(error.networkResponse.data, "utf-8");
if (!responseBody.equalsIgnoreCase("")) {
JSONObject data = new JSONObject(responseBody);
listener.onResult(data + "", responseCode);
//listener.onResult(error.toString(), WebAPIConstants.VOLLEY_ERROR);
Log.e("ERROR", error.toString() + "");
} else {
listener.onResult("", responseCode);
}
}
else
listener.onResult("", responseCode);
} catch (JSONException e) {
} catch (UnsupportedEncodingException errorr) {
} catch (Exception e) {
Crashlytics.logException(e);
}
}
if (showDialog == true) {
try {
mOverlayDialog.dismiss();
} catch (Exception e) {
// Crashlytics.logException(e);
}
try {
materialDialog.dismiss(); // To hide the progress bar
} catch (Exception e) {
// Crashlytics.logException(e);
}
}
try {
if (error instanceof TimeoutError) {
AlertDialogManager.showAlertDialog(mContext, mContext.getResources().getString(R.string.timeout_error_title), mContext.getResources().getString(R.string.timeout_error_string), new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
}
});
} else if (error instanceof NoConnectionError) {
if (CheckInternetConnection.haveNetworkConnection(mContext)) {
AlertDialogManager.showAlertDialog(mContext, mContext.getResources().getString(R.string.timeout_error_title), mContext.getResources().getString(R.string.timeout_error_string), new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
}
});
} else {
AlertDialogManager.showAlertDialog(mContext, mContext.getResources().getString(R.string.no_internet_title), mContext.getResources().getString(R.string.no_internet_message), new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
}
});
}
}
} catch (Exception e) {
Crashlytics.logException(e);
}
}
(已以字节码发送图像),在使用字符串请求时,正在上传图像,但大小为1kB,但在服务器上打开了文件(已以字节码发送图像)。
字符串请求
StringRequest stringRequest=new StringRequest(Request.Method.PUT, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
if (listener != null) {
Log.e("Response", response + "");
if (showDialog == true) {
try {
mOverlayDialog.dismiss();
} catch (Exception e) {
// Crashlytics.logException(e);
}
try {
materialDialog.dismiss(); // To hide the progress bar
} catch (Exception e) {
// Crashlytics.logException(e);
}
}
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
if (listener != null) {
try {
if(error.networkResponse!=null && error.networkResponse.data!=null) {
String responseBody = new String(error.networkResponse.data, "utf-8");
if (!responseBody.equalsIgnoreCase("")) {
JSONObject data = new JSONObject(responseBody);
listener.onResult(data + "", responseCode);
//listener.onResult(error.toString(), WebAPIConstants.VOLLEY_ERROR);
Log.e("ERROR", error.toString() + "");
} else {
listener.onResult("", responseCode);
}
}
else
listener.onResult("", responseCode);
} catch (JSONException e) {
} catch (UnsupportedEncodingException errorr) {
} catch (Exception e) {
Crashlytics.logException(e);
}
}
if (showDialog == true) {
try {
mOverlayDialog.dismiss();
} catch (Exception e) {
// Crashlytics.logException(e);
}
try {
materialDialog.dismiss(); // To hide the progress bar
} catch (Exception e) {
// Crashlytics.logException(e);
}
}
try {
if (error instanceof TimeoutError) {
AlertDialogManager.showAlertDialog(mContext, mContext.getResources().getString(R.string.timeout_error_title), mContext.getResources().getString(R.string.timeout_error_string), new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
}
});
} else if (error instanceof NoConnectionError) {
if (CheckInternetConnection.haveNetworkConnection(mContext)) {
AlertDialogManager.showAlertDialog(mContext, mContext.getResources().getString(R.string.timeout_error_title), mContext.getResources().getString(R.string.timeout_error_string), new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
}
});
} else {
AlertDialogManager.showAlertDialog(mContext, mContext.getResources().getString(R.string.no_internet_title), mContext.getResources().getString(R.string.no_internet_message), new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
}
});
}
}
} catch (Exception e) {
Crashlytics.logException(e);
}
}
})
{
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
if (listener!=null) {
listener.onResult(mStatusCode + "", responseCode);
}
mStatusCode = response.statusCode;
return super.parseNetworkResponse(response);
}
@Override
protected Map<String, String> getParams() throws AuthFailureError {
return parameters;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/octet-stream");
return headers;
}
};
stringRequest.setRetryPolicy(new DefaultRetryPolicy(120000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
try {
stringRequest.setShouldCache(false);
queue.getCache().clear();
queue.add(stringRequest);
} catch (Exception e) {
Crashlytics.logException(e);
}
也尝试过Multipart请求,但出现了身份验证错误等错误。
多部分请求,其中文档网址与邮递员中的网址相同
为以下请求添加了相关性:
编译组:' org.apache.httpcomponents ',名称:' httpclient-android ',版本:' 4.3.5.1 '编译(' org . Apache . http components:http time:4.3 '){排除模块:" httpclient" }
多部分请求请求类
包spice.mudra.csp_cred;
import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyLog;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
public class MultipartRequestAWS extends Request<String> {
private MultipartEntity entity = new MultipartEntity();
private static final String FILE_PART_NAME = "file";
private static final String STRING_PART_NAME = "text";
private final Response.Listener<String> mListener;
private final File mFilePart;
private final String mStringPart;
public MultipartRequestAWS(String url, Response.Listener<String> listener, Response.ErrorListener errorListener,File file, String stringPart) {
super(Method.POST, url, errorListener);
mListener = listener;
mFilePart = file;
mStringPart = stringPart;
buildMultipartEntity();
}
private void buildMultipartEntity()
{
entity.addPart(FILE_PART_NAME, new FileBody(mFilePart));
try
{
entity.addPart(STRING_PART_NAME, new StringBody(mStringPart));
}
catch (UnsupportedEncodingException e)
{
VolleyLog.e("UnsupportedEncodingException");
}
}
@Override
public String getBodyContentType()
{
return "application/octet-stream";
}
@Override
public byte[] getBody() throws AuthFailureError
{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try
{
entity.writeTo(bos);
}
catch (IOException e)
{
VolleyLog.e("IOException writing to ByteArrayOutputStream");
}
return bos.toByteArray();
}
@Override
protected Response<String> parseNetworkResponse(NetworkResponse response)
{
return Response.success("Uploaded", getCacheEntry());
}
@Override
protected void deliverResponse(String response)
{
mListener.onResponse(response);
}
}
多部分请求****
MultipartRequestAWS request = new MultipartRequestAWS(docUrl, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.e("Responce", "" + response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("Responce", "" + error);
}
}, outputFile, imageArray.toString()
);
request.setRetryPolicy(new DefaultRetryPolicy(300000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
//adding request to request queue
// if(!Constants.IS_PRODUCTION) {
Volley.newRequestQueue(this).add(request);
// }else{
// Volley.newRequestQueue(getActivity(), new OKHttpStack(new URL(request.getUrl()).getHost())).add(request);
//
// // Volley.newRequestQueue(getActivity(), new HurlStack(null, newSslSocketFactory())).add(request);
// }
尝试了其他多部分请求
private final String boundary = "apiclient-" + System.currentTimeMillis();
private final String mimeType = "multipart/form-data;boundary=" + boundary;
//multipartBody is byte code of image to be uploaded
MultipartRequest request = new MultipartRequest(url, null, mimeType, multipartBody, new Response.Listener<NetworkResponse>() {
@Override
public void onResponse(NetworkResponse response) {
try {
mOverlayDialogAsync.dismiss();
} catch (Exception e) {
Crashlytics.logException(e);
}
try {
materialDialogAsync.dismiss(); // To hide the progress bar
} catch (Exception e) {
Crashlytics.logException(e);
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
try {
mOverlayDialogAsync.dismiss();
} catch (Exception e) {
Crashlytics.logException(e);
}
try {
materialDialogAsync.dismiss(); // To hide the progress bar
} catch (Exception e) {
Crashlytics.logException(e);
}
try {
// getting json string form the response obtained from server
String jsonString = new String(error.toString());
Log.e("response multipart", jsonString);
} catch (Exception e) {
Crashlytics.logException(e);
}
try {
//Network errors handling
if (error instanceof TimeoutError) {
AlertDialogManager.showAlertDialog(CustomDialogNetworkRequest.this, getResources().getString(R.string.timeout_error_title), getResources().getString(R.string.timeout_error_string), new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
}
});
} else if (error instanceof NoConnectionError) {
if (spice.mudra.utils.CheckInternetConnection.haveNetworkConnection(AddYourProffDetails.this)) {
AlertDialogManager.showAlertDialog(AddYourProffDetails.this, getResources().getString(R.string.timeout_error_title), getResources().getString(R.string.timeout_error_string), new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
}
});
} else {
AlertDialogManager.showAlertDialog(AddYourProffDetails.this, getResources().getString(R.string.no_internet_title), getResources().getString(R.string.no_internet_message), new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
}
});
}
} else {
AlertDialogManager.showAlertDialog(AddYourProffDetails.this, "", "Something went wrong. Please try again.", new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
}
});
}
} catch (Exception e) {
Crashlytics.logException(e);
}
}
});
//setting timeout to multipart request
request.setRetryPolicy(new DefaultRetryPolicy(300000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
//adding request to request queue
Log.i("++++++++++", "Request body: " + new String(request.getBody()));
Volley.newRequestQueue(CustomDialogNetworkRequest.this).add(request);
} catch (Exception e) {
Crashlytics.logException(e);
}
}
请同样帮忙。
请找邮递员截图参考。这也有我正在使用的URL类型。
为了上传图像文件,向StringRequest对象添加以下函数。这里outputFileUri是您想要上传的文件的Uri。s3Url是您想要放置图像文件的s3 bucket url。
StringRequest putRequest = new StringRequest(Request.Method.PUT, s3Url,
new Response.Listener<String>()
{
@Override
public void onResponse(String response) {
// response
}
},
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error) {
// error
}
}){
@Override
public String getBodyContentType() {
return "image/jpeg";
}
@Override
public byte[] getBody() throws AuthFailureError {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
InputStream inputStream = mContext.getContentResolver().openInputStream(outputFileUri);
byte[] b = new byte[8192];
for (int readNum; (readNum = inputStream.read(b)) != -1; ) {
bos.write(b, 0, readNum);
}
inputStream.close();
return bos.toByteArray();
} catch (Exception e) {
Log.d(TAG, e.toString());
}
return null;
}
};
Volley.newRequestQueue(this).add(putRequest);
这是我用来发出POST请求的一段代码。 在以前的项目中,一切都很好地工作,但现在的问题是,我想在帖子正文中包括布尔值和字符串值。 正文如下:{"email":"username@mail.com","密码":"Somepassword","rememberPassword": false,"ip_address":"152.57.31.41","isCaptchaEn的": false} 我不熟悉
我的代码有一个问题,对我来说效果很好,但当我使用代理进行拦截时,它会向我发送一个双重请求。我想解决这个错误,只发送一次。我在查看网页时发现了一个类似的问题,但我对这种语言还不熟悉,不知道如何实现它。 当有慢速请求时,Android截击双发 我的代码:
当我在android截击请求的OneErrorRepsonse中收到错误时,我想重试该请求。我怎样才能做到这一点?
我正在用GoogleVolley Api创建一个android应用程序,它处理我的应用程序和php脚本之间的连接。出于某种原因,该应用程序没有向我的服务器发送任何数据,也许这里的某个人可以找到它? 我的方法被正确调用,但是当我尝试打印它时,它返回null!一切实际上都在工作,除了数据没有正确传递,我相信,因为我的php脚本抱怨变量为空
我正在执行使用Python请求库上传文件的简单任务。我搜索了Stack Overflow,似乎没有人遇到同样的问题,即服务器无法接收文件: 我正在用我的文件名填充upload_file关键字的值,因为如果我把它留空,它会说 现在我得到了 只有当文件为空时才会显示。所以我一直在思考如何成功地发送文件。我知道这个文件是有效的,因为如果我去这个网站手动填写表单,它会返回一个匹配对象的列表,这就是我想要的
我正在使用截击与API交互。我需要向返回JSON数组的服务发送post请求(带参数)。 JsonObjectRequest有一个构造函数,它接受一个方法和一组参数 但是JSONArrayRequest(我需要的一个)只有一个构造函数的形式 我如何才能使其发送包含数据的POST请求?