@SuppressWarnings("ALL")publicclassVolleyMultipartRequest extends Request<NetworkResponse>{private final String twoHyphens ="--";private final String lineEnd ="\r\n";private final String boundary ="apiclient-"+System.currentTimeMillis();privateResponse.Listener<NetworkResponse> mListener;privateResponse.ErrorListener mErrorListener;privateMap<String,String> mHeaders;publicVolleyMultipartRequest(int method,String url,Response.Listener<NetworkResponse> listener,Response.ErrorListener errorListener){
super(method, url, errorListener);this.mListener = listener;this.mErrorListener = errorListener;}@OverridepublicMap<String,String> getHeaders() throws AuthFailureError{return(mHeaders != null)? mHeaders : super.getHeaders();}@OverridepublicString getBodyContentType(){return"multipart/form-data;boundary="+ boundary;}@Overridepublic byte[] getBody() throws AuthFailureError{ByteArrayOutputStream bos =newByteArrayOutputStream();DataOutputStream dos =newDataOutputStream(bos);try{// populate text payloadMap<String,String> params = getParams();if(params != null && params.size()>0){
textParse(dos, params, getParamsEncoding().trim());}// populate data byte payloadMap<String,DataPart> data = getByteData();if(data != null && data.size()>0){
dataParse(dos, data);}// close multipart form data after text and file data
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);return bos.toByteArray();}catch(IOException e){
e.printStackTrace();}return null;}/**
* Custom method handle data payload.
*
* @return Map data part label with data byte
* @throws AuthFailureError
*/protectedMap<String,DataPart> getByteData() throws AuthFailureError{return null;}@OverrideprotectedResponse<NetworkResponse> parseNetworkResponse(NetworkResponse response){try{returnResponse.success(
response,HttpHeaderParser.parseCacheHeaders(response));}catch(Exception e){returnResponse.error(newParseError(e));}}@Overrideprotectedvoid deliverResponse(NetworkResponse response){
mListener.onResponse(response);}@Overridepublicvoid deliverError(VolleyError error){
mErrorListener.onErrorResponse(error);}/**
* Parse string map into data output stream by key and value.
*
* @param dataOutputStream data output stream handle string parsing
* @param params string inputs collection
* @param encoding encode the inputs, default UTF-8
* @throws IOException
*/privatevoid textParse(DataOutputStream dataOutputStream,Map<String,String> params,String encoding) throws IOException{try{for(Map.Entry<String,String> entry : params.entrySet()){
buildTextPart(dataOutputStream, entry.getKey(), entry.getValue());}}catch(UnsupportedEncodingException uee){thrownewRuntimeException("Encoding not supported: "+ encoding, uee);}}/**
* Parse data into data output stream.
*
* @param dataOutputStream data output stream handle file attachment
* @param data loop through data
* @throws IOException
*/privatevoid dataParse(DataOutputStream dataOutputStream,Map<String,DataPart> data) throws IOException{for(Map.Entry<String,DataPart> entry : data.entrySet()){
buildDataPart(dataOutputStream, entry.getValue(), entry.getKey());}}/**
* Write string data into header and data output stream.
*
* @param dataOutputStream data output stream handle string parsing
* @param parameterName name of input
* @param parameterValue value of input
* @throws IOException
*/privatevoid buildTextPart(DataOutputStream dataOutputStream,String parameterName,String parameterValue) throws IOException{
dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"");
dataOutputStream.write(parameterName.getBytes("UTF-8"));
dataOutputStream.writeBytes(lineEnd);
dataOutputStream.writeBytes("Content-Type: text/plain; charset=UTF-8"+ lineEnd);
dataOutputStream.writeBytes(lineEnd);
dataOutputStream.write(parameterValue.getBytes("UTF-8"));
dataOutputStream.writeBytes(lineEnd);}/**
* Write data file into header and data output stream.
*
* @param dataOutputStream data output stream handle data parsing
* @param dataFile data byte as DataPart from collection
* @param inputName name of data input
* @throws IOException
*/privatevoid buildDataPart(DataOutputStream dataOutputStream,DataPart dataFile,String inputName) throws IOException{
dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
dataOutputStream.writeBytes("Content-Disposition: form-data; name=\""+
inputName +"\"; filename=\""+ dataFile.getFileName()+"\""+ lineEnd);if(dataFile.getType()!= null &&!dataFile.getType().trim().isEmpty()){
dataOutputStream.writeBytes("Content-Type: "+ dataFile.getType()+ lineEnd);}
dataOutputStream.writeBytes(lineEnd);ByteArrayInputStream fileInputStream =newByteArrayInputStream(dataFile.getContent());int bytesAvailable = fileInputStream.available();int maxBufferSize =1024*1024;int bufferSize =Math.min(bytesAvailable, maxBufferSize);
byte[] buffer =new byte[bufferSize];int bytesRead = fileInputStream.read(buffer,0, bufferSize);while(bytesRead >0){
dataOutputStream.write(buffer,0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize =Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer,0, bufferSize);}
dataOutputStream.writeBytes(lineEnd);}classDataPart{privateString fileName;private byte[] content;privateString type;publicDataPart(){}DataPart(String name, byte[] data){
fileName = name;
content = data;}String getFileName(){return fileName;}
byte[] getContent(){return content;}String getType(){return type;}}}
privatevoid uploadPDF(final String pdfname,Uri pdffile){
progressDialog =ProgressDialog.show(uploadved.this,"جارى ارسال الفيديو","برجاء الانتظار",false,false);InputStream iStream = null;try{
iStream = getContentResolver().openInputStream(pdffile);
final byte[] inputData = getBytes(iStream);VolleyMultipartRequest volleyMultipartRequest =newVolleyMultipartRequest(Request.Method.POST,URLphp,newResponse.Listener<NetworkResponse>(){@Overridepublicvoid onResponse(NetworkResponse response){Log.d("ressssssoo",newString(response.data));Toast.makeText(uploadved.this,newString(response.data),Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
rQueue.getCache().clear();try{JSONObject jsonObject =newJSONObject(newString(response.data));Toast.makeText(getApplicationContext(), response.toString(),Toast.LENGTH_SHORT).show();}catch(JSONException e){Toast.makeText(uploadved.this,"",Toast.LENGTH_SHORT).show();}}},newResponse.ErrorListener(){@Overridepublicvoid onErrorResponse(VolleyError error){Toast.makeText(getApplicationContext(), error.getMessage(),Toast.LENGTH_SHORT).show();}}){/*
* If you want to add more parameters with the image
* you can do it here
* here we have only one parameter with the image
* which is tags
* */@OverrideprotectedMap<String,String> getParams() throws AuthFailureError{Map<String,String> params =newHashMap<>();
params.put("rw", shall.getInstance(uploadved.this).getuserShow());
params.put("imrwedagsh", shall.getInstance(uploadved.this).getimage());
params.put("idrewdus", shall.getInstance(uploadved.this).getid());
params.put("tirwgfdtel",enwanvido);return params;}/*
*pass files using below method
* */@OverrideprotectedMap<String,DataPart> getByteData(){Map<String,DataPart> params =newHashMap<>();
params.put("uyt",newDataPart(pdfname ,inputData));Log.d("testerget work","workingpartdata");return params;}};
volleyMultipartRequest.setRetryPolicy(newDefaultRetryPolicy(0,DefaultRetryPolicy.DEFAULT_MAX_RETRIES,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
rQueue =Volley.newRequestQueue(uploadved.this);
rQueue.add(volleyMultipartRequest);}catch(FileNotFoundException e){Toast.makeText(this,"لم يتم التعرف على الملف ",Toast.LENGTH_SHORT).show();}catch(IOException e){Toast.makeText(this,"هناك مشكلة بالانترنت ",Toast.LENGTH_SHORT).show();}}
هاتان الصفحتان للتعامل مع الخدمة المطلوبة
تم التعديل في بواسطة Mustafa Suleiman تعديل عنوان السؤال
السؤال
Drive Man
هاتان الصفحتان للتعامل مع الخدمة المطلوبة
تم التعديل في بواسطة Mustafa Suleimanتعديل عنوان السؤال
4 أجوبة على هذا السؤال
Recommended Posts
انضم إلى النقاش
يمكنك أن تنشر الآن وتسجل لاحقًا. إذا كان لديك حساب، فسجل الدخول الآن لتنشر باسم حسابك.