I wanna send a PDF file stored in internal storage ( InternalStrorage/PDF/OCK.pdf )
I already sent String Data to my php server using Android Volley without problems via this function:
private void upload(){
StringRequest stringRequest = new StringRequest(Request.Method.POST, UploadURL,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
String Response = jsonObject.getString("response");
Toast.makeText(getApplicationContext(),Response, Toast.LENGTH_LONG).show();
selectedimage.setImageResource(0);
selectedimage.setVisibility(View.GONE);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}
){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("date",DateFormat.getDateTimeInstance().format(new Date()).toString());
params.put("description",editTextDescription.getText().toString());
params.put("statut", whatstatutis());
params.put("action",editTextImediatActionTaken.getText().toString());
return params;
}
};
MySingleton.getInstance(getApplicationContext()).addTorequesteque(stringRequest);
}
I wanna send the PDF file with my data in the same time.
Finally i find the solution.
1- Just convert the PDF to to byte array
2- Byte Array to base64
3- Send it like normal strings
byte[] data = null;
File filessss = new File(Link_Of_The_PDF.pdf);
try {
data = FileUtils.readFileToByteArray(filessss);
} catch (IOException e) {
e.printStackTrace();
}
return Base64.encodeToString(data, Base64.DEFAULT);
Related
I wanted to upload a file from my android internal storage to Any cloud storage(ex.google drive,One drive etc)since kloudless provides an api to upload file to any cloud storage using accesstoken I wanted to use the same api for uploading the file (https://api.kloudless.com/v1/accounts/accountid+/storage/files/).
I tried it through postman I am able to upload the file
Now I tried through android volley I am able to create the file in the cloud but there is no data inside it. Here is my code
public class MainActivity extends AppCompatActivity {
Button b;
TextView TV;
File myFile;
String responseString;
String path;
public String BASE_URL = "https://api.kloudless.com";
private static final int FILE_SELECT_CODE = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TV = findViewById(R.id.textView);
b = findViewById(R.id.button);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showFileChooser();
}
});
}
private void showFileChooser() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(
Intent.createChooser(intent, "Select a File to Upload"),
FILE_SELECT_CODE);
} catch (android.content.ActivityNotFoundException ex) {
// Potentially direct the user to the Market with a Dialog
Toast.makeText(this, "Please install a File Manager.",
Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == FILE_SELECT_CODE) {
if (resultCode == RESULT_OK) {
// Get the Uri of the selected file
Uri uri = data.getData();
Log.d("TAG", "File Uri: " + uri.toString());
// Get the path
String path = null;
try {
path = FileUtils.getPath(this, uri);
} catch (URISyntaxException e) {
e.printStackTrace();
}
Log.d("TAG", "File Path: " + path);
try {
data();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
super.onActivityResult(requestCode, resultCode, data);
}
public void data() throws FileNotFoundException, UnsupportedEncodingException {
final String url = BASE_URL + "/v1/accounts/" + "accountid" + "/storage/files/";
final RequestQueue queue = Volley.newRequestQueue(this);
HashMap<String, Object> params = new HashMap<String, Object>();
params.put( "file","somedata");
JSONObject Body=new JSONObject(params);
final JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url,Body, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
// response
Log.d("Response", response.toString());
}
},
new ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", error.toString());
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> params = new HashMap<String, String>();
params.put("Authorization", "Bearer Bearerkey");
params.put("Content-Type", "form-data");
params.put("X-Kloudless-Metadata", "{\"parent_id\":\"root\",\"name\":\"testdone.txt\"}");
// params.put("Content-Length", Space);
return params;
}
};
queue.add(request);
}
Please help me how to send the file in body of my request
I work at Kloudless and while I am not very familiar with the Android Volley, the issue here appears to be that you are setting a JSON body with the incorrect content type. In order to replicate the Postman request, you would need to use a multipart file upload instead, as described here: How to upload file using Volley library in android? The file would need to be added to a field called file, e.g entity.addPart("file", new FileBody(new File("....")));
In order for there to be more efficient handling on the server side (for larger files), the request performed should instead include the binary file contents in the request body and have the header Content-Type: application/octet-stream. Based on some cursory searching, it seems like the Volley library doesn't make that very easy so it might be best to try a different library.
Finally found the simple solution to upload a file to api
RequestQueue queue = Volley.newRequestQueue(this);
String url = BASE_URL + "/v1/accounts/" + "353284419" + "/storage/files/";
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Toast.makeText(MainActivity.this, response, Toast.LENGTH_LONG).show();
// response
Log.d("Response", response);
}
},
new ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", error.toString());
}
}
) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("Authorization", "Bearer ix7wW4CFJsHxhttg42qsO6HNNRPh06");
params.put("Content-Type", "application/octet-stream");
params.put("X-Kloudless-Metadata", "{\"parent_id\":\"root\",\"name\":\"testing uplodes.pdf\"}");
// params.put("Content-Length", Space);
return params;
}
#Override
public byte[] getBody() throws com.android.volley.AuthFailureError {
File f=new File(path);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
FileInputStream fis = null;
try {
fis = new FileInputStream(f);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
byte[] bytesArray = new byte[(int)f.length()];
try {
fis.read(bytesArray);
} catch (IOException e) {
e.printStackTrace();
}
return bytesArray;
};
};
postRequest.setRetryPolicy(new DefaultRetryPolicy(
40000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
queue.add(postRequest);
}
just convert the file into binary array and send it in the body
I'm using Android studio with Nodejs. To get data, I want to get Json from nodejs server using 'volley' At server( Nodejs, Express) delivery Tow JSon
res.write(JSON.stringify(results));
res.write(JSON.stringify(hot));
i want to get these Jsons from server to Android but fail... i can get only one JSON which is delivered first , this one
res.write(JSON.stringify(results));
how can i get two JSON ?? without merge JSON
public void onButton1Clicked(View v){
String url=editText.getText().toString();
StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
println(response);
JSONArray jarray= new JSONArray(response);
for(int i=0;i<jarray.length();i++)
{
JSONObject Jobs=jarray.getJSONObject(i);
String title=Jobs.getString("title");
String content=Jobs.getString("content");
println(" title : " + title);
println(" content : " + content);
}
} catch (Exception e) {
println("에러남!");
e.printStackTrace();
}
}
},new Response.ErrorListener(){
#Override
public void onErrorResponse(VolleyError error) {
println("error!###");
error.printStackTrace();
}
}
){
#Override
protected Map<String, String> getParams(){
Map<String, String> params = new HashMap<>();
return params;
}
};
request.setShouldCache(false);
Volley.newRequestQueue(this).add(request);
println("웹 서버에 요청함 : "+url);
}
I've been looking for a way to upload a file using Volley API using the PUT method. All I've seen so far are through MultiPart POST method which aren't applicable to my case.
Assuming I can't change anything on the server side and I'm stuck with using PUT. How do I achieve this in volley?
Note that I only have the url where to upload the file and the file itself.
For uploading image file add the following functions to your StringRequest object.
Here outputFileUri is the Uri of the file which you want to upload.
#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;
}
use the basic concept of PUT method
url = "your URL";
StringRequest putRequest = new StringRequest(Request.Method.PUT, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
// response
Log.d("Response", response);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", response);
}
}){
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String> ();
params.put("name", "file_name");
return params;
}
}; RequestQueue queue = Volley.newRequestQueue(this);
queue.add(putRequest);
I have following format of posting data to server. I want to post these data to server using volley library and following request contains multiple images' base64 content also. I am passing this as StringRequest i got the error of invalid JSON data format. How can i post following data to server? Or any other useful way to pass following data to server then also let me know. So that i can solve this problem and efficiently can upload on server.
{
"TakeoffID": "2",
"ViewPhoto1": "image base64 content",
"ViewPhoto2": "image base64 content",
"LineItems": [
{
"OrderLineid": "964",
"OrderLinePhoto1": "image base64 content",
"OrderLinePhoto2": "image base64 content"
},
{
"OrderLineid": "963",
"OrderLinePhoto1": "image base64 content",
"OrderLinePhoto2": "image base64 content"
}
]
}
===========
Following is my code to upload above data:
private void uploadImage(final CustomerBean bean,final String line_items)
{
// Showing the progress dialog
final ProgressDialog loading = ProgressDialog.show(mActivity, "Uploading...", "Please wait...", false, false);
StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.POST, Const.API_SYNC_ALL_DATA, new Response.Listener<String>() {
#Override
public void onResponse(String s)
{
loading.dismiss();
Log.print("======UPLOAD IMAGE=====", s);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError)
{
loading.dismiss();
Toast.makeText(mActivity, volleyError.getMessage().toString(), Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError
{
Map<String, String> params = new Hashtable<String, String>();
params.put("TakeoffID", "2");
params.put("ViewPhoto1", bean.photo1);
params.put("ViewPhoto2", bean.photo2);
params.put("LineItems", line_items);
// returning parameters
return params;
}
};
// Creating a Request Queue
RequestQueue requestQueue = Volley.newRequestQueue(mActivity);
// Adding request to the queue
requestQueue.add(stringRequest);
}
===========================
And I am getting following error from server.
[
{
"code": "-1",
"message": "The json data format is incorrect"
}
]
You can also use following block of code for pass json object to Volley as a parameter. Just check it once.
JSONObject data= new JSONObject();
data.accumulate("username", "mobileGps");
data.accumulate("password", "9565551236");
JSONObject total= new JSONObject();
total.put("data",data);
json = jsonObjectNew.toString();
IMO, you can refer to my following sample code:
try {
RequestQueue requestQueue = Volley.newRequestQueue(this);
String URL = "http://...";
// Prepares POST data...
JSONObject jsonBody = new JSONObject();
jsonBody.put("TakeoffID", "2");
jsonBody.put("ViewPhoto1", "image base64 content");
jsonBody.put("ViewPhoto2", "image base64 content");
// "OrderLineid": "964"...
JSONObject jsonObject1 = new JSONObject();
jsonObject1.put("OrderLineid","964");
jsonObject1.put("OrderLinePhoto1","image base64 content");
jsonObject1.put("OrderLinePhoto2","image base64 content");
// "OrderLineid": "963"...
JSONObject jsonObject2 = new JSONObject();
jsonObject2.put("OrderLineid","963");
jsonObject2.put("OrderLinePhoto1","image base64 content");
jsonObject2.put("OrderLinePhoto2","image base64 content");
JSONArray jsonArray = new JSONArray();
jsonArray.put(jsonObject1);
jsonArray.put(jsonObject2);
// "LineItems"...
jsonBody.put("LineItems", jsonArray);
final String mRequestBody = jsonBody.toString();
// Volley request...
StringRequest request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("VOLLEY", error.toString());
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return mRequestBody == null ? null : mRequestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s",
mRequestBody, "utf-8");
return null;
}
}
};
requestQueue.add(request);
} catch (JSONException e) {
e.printStackTrace();
}
Hope it helps!
I have not used volley library much. i have read the tutorials. i want to send data to a url which which will enter that data in database. i have tried the following code but its not working. data is not entered in the database.
String url = "http://tipseducation.com/system/eadmin/insertschedule/";
StringRequest sr = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//Valid Response
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//error message
}
}) {
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("appt_name", ed_name);
params.put("appt_email", ed_email);
params.put("appt_contact", ed_contact);
params.put("appt_date", ed_date);
params.put("appt_time", ed_time);
params.put("appt_service", ed_spinner);
return params;
}
};
can anyone please help me. iam new to this
Instead of getHeaders, you should use getBody for your POST request.
You can refer to my following working sample code (replace my JSONObject and Url by yours). Hope this helps!
...
try {
RequestQueue queue = Volley.newRequestQueue(this);
jsonBody = new JSONObject();
jsonBody.put("Title", "Android Volley POST DATA Demo");
jsonBody.put("Author", "BNK");
jsonBody.put("Date", "2015/09/17");
requestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(1, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// do something...
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// do something...
}
}) {
#Override
public String getBodyContentType() {
return "application/json; charset=utf-8";
}
#Override
public byte[] getBody() throws AuthFailureError {
try {
return requestBody == null ? null : requestBody.getBytes("utf-8");
} catch (UnsupportedEncodingException uee) {
e.printStackTrace();
return null;
}
}
};
queue.addToRequestQueue(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}
...