Volley doesnot connect with flask server - android

My java code is not connect with flask. It doesn't give any error or response. Program run infinitely.
When i try to connect it is not going on response or on error function. After completing function call it start running and never stop.
Java Code:
Button button;
RequestQueue rQueue;
String url ="http://127.0.0.1:5000/predict";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
rQueue = Volley.newRequestQueue(MainActivity.this);
}
public void predict(View view){
UploadTwoImages();
}
public String getStringImage(Bitmap bmp) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
public void UploadTwoImages() {
Bitmap icon = BitmapFactory.decodeResource(getResources(),R.drawable.logo);
final String imageOne = getStringImage(icon);
final ProgressDialog pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Registration is in Process Please wait...");
pDialog.show();
StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String s) {
pDialog.dismiss();
Log.d("JSONResult", s);
try {
JSONObject jObject = new JSONObject(s);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
}
}) {
//adding parameters to send
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("image", imageOne);
return parameters;
}
};
request.setRetryPolicy(new DefaultRetryPolicy(
90000,
0,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
request.setShouldCache(false);
rQueue.add(request);
}
Flask Server Code:
#app.route('/predict', methods=['GET', 'POST'])
def upload():
if request.method == "POST":
if request.files:
output={}
image = request.files["image"]
print(request.files)
basepath = os.path.dirname(__file__)
file_path = os.path.join(
basepath, 'uploads', secure_filename(image.filename))
print(image.filename)
image.save(file_path)
return str([1])
return "Error"
if __name__ == '__main__':
app.run(debug=True)
url = ipv4address:portNumber/apiName

In android manifest add following 2 lines and it works for me.
android:usesCleartextTraffic="true"
<uses-permission android:name="android.permission.INTERNET"/>

Related

how to see json data send to server in volley in android

I'm sending json data to server successfully.But problem in sending image.
I try the following thing:-
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
private void uploadImage(){
//Showing the progress dialog
final ProgressDialog loading = ProgressDialog.show(this,"Uploading...","Please wait...",false,false);
StringRequest stringRequest = new StringRequest(Request.Method.POST, "http://toootapp.dreamsapps.com/ToootWebservice.asmx/SaveImage",
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
Log.e("img Response",s.toString().trim());
//Disimissing the progress dialog
loading.dismiss();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Log.e("onErrorResponse=",getIntent().getStringExtra("path"));
//Dismissing the progress dialog
loading.dismiss();
//Showing toast
// Toast.makeText(SaveImageOnServerActivity.this, volleyError.getMessage().toString(), Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
//Converting Bitmap to String
// Log.e("Path=",getIntent().getStringExtra("path"));
Bitmap myBitmap = BitmapFactory.decodeFile(new File(getIntent().getStringExtra("path")).getAbsolutePath());
String image = getStringImage(myBitmap);
//Getting Image Name
String name = "Computer";//editTextName.getText().toString().trim();
//Creating parameters
Map<String,String> params = new Hashtable<String, String>();
//Adding parameters
params.put("base64Image", image);
params.put("Tags", "Computer");
//returning parameters
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
};
//Creating a Request Queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
So I just want to check which json string is going to server.
Is there any way I can see what json string in the following form
{
"base64Image": "",
"Email": "abc#gmail.com",
"MobileNo": "1234567890",
"Website": "www.gameneeti.com",
"Industry": "Computer"
}
I send.
I want to print in log this string.
Thanks.

Upload image to server c# android

Well this might sound a question that has been asked few often times but I could not come with a solution for the same.I want to upload image to server C#, i got codes for how to send image but don't know exactly how to use it. Please correct my code if there is something wrong and any idea about server side code for the same correction.
ProgressDialog progressDialog = new ProgressDialog(AddPropertyThird.this);
progressDialog.setMessage("Uploading, please wait...");
progressDialog.show();
//converting image to base64 string
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
final String imageString = Base64.encodeToString(imageBytes,Base64.DEFAULT);
//sending image to server
StringRequest request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String s) {
progressDialog.dismiss();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
Toast.makeText(AddPropertyThird.this, "Some error occurred -> " + volleyError, Toast.LENGTH_LONG).show();
}
}) {
//adding parameters to send
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("imageFile", imageString);
return parameters;
}
};
RequestQueue rQueue = Volley.newRequestQueue(AddPropertyThird.this);
rQueue.add(request);
}
});
}
Logcat error
[879] BasicNetwork.performRequest: Unexpected response code 500
02-09 12:33:24.106 2 E/volleyerror: com.android.volley.ServerError

Volley post request not sending data properly

I'm trying to send a base64 encoded string to a server over volley but its not sending properly. When i use httpbin this is the response
"args": {},
I/System.out: "data": "",
I/System.out: "files": {},
I/System.out: "form": { "/9j/4AAQSkZJRgABAQAASABIAAD/4QBMRXhpZgAATU0AKgAAAAgAAgESAAMAAAABAAEAAIdpAAQAAAABAAAAJgAAAAAAAqACAAQAAAABAAACiaADAAQAAAABAAAARQAAAAD/4QkhaHR0cDovL25zLmFkb2JlLmN...(image base64)
I/System.out: },
where the image data is in the form. However i need it in data.
public static String rawOutput = "dadsdas";
private Button buttonChoose;
private Button buttonUpload;
public String image;
private ImageView imageView;
private Button postText;
private EditText editTextName;
private Bitmap bitmap;
private int PICK_IMAGE_REQUEST = 1;
private String UPLOAD_URL ="https://httpbin.org/post";
private String KEY_IMAGE = "Content-Type";
private String KEY_NAME = "name";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post_image);
buttonChoose = (Button) findViewById(R.id.buttonChoose);
postText = (Button) findViewById(R.id.postText);
buttonUpload = (Button) findViewById(R.id.buttonUpload);
imageView = (ImageView) findViewById(R.id.imageView);
buttonChoose.setOnClickListener(this);
buttonUpload.setOnClickListener(this);
}
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 50, baos);
byte[] imageBytes = baos.toByteArray();
System.out.println(imageBytes);
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
private void uploadImage() throws JSONException {
//Showing the progress dialog
final ProgressDialog loading = ProgressDialog.show(this,"Uploading...","Please wait...",false,false);
// JSONObject jsonBody = new JSONObject();
// jsonBody.put(getStringImage(bitmap), "");
//final String mRequestBody = jsonBody.toString();
StringRequest stringRequest = new StringRequest(Request.Method.POST, UPLOAD_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
loading.dismiss();
System.out.println(s);
Toast.makeText(PostImage.this, s , Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
loading.dismiss();
String json = null;
NetworkResponse response = volleyError.networkResponse;
if(response != null && response.data != null){
switch(response.statusCode){
case 400:
json = new String(response.data);
if(json != null) System.out.println(json);
System.out.println(json.getClass().getSimpleName());
break;
}
//Additional cases
}
Toast.makeText(PostImage.this, volleyError.getMessage(), Toast.LENGTH_LONG).show();
}
}){
// #Override
// public String getBodyContentType() {
// return "text/plain; charset=utf-8";
// }
// #Override
// public byte[] getBody() {
// byte[] body = new byte[0];
// try {
// body = ("/9j/4AAQSkZJRgABAQAASABIAAD/4QBMRXhpZgAATU0AKgAAAAgAAgESAAMAAAABAAEAAIdpAAQAAAABAAAAJgAAAAAAAqACAAQAAAABAAACiaADAAQAAAABAAAARQAAAAD/4QkhaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLwA8P3hwYWNrZXQgYmVnaW49Iu+7vyIgaWQ9Ilc1TTBNcENlaGlIenJlU3pOVGN6a2M5ZCI/PiA8eDp4bXBtZXRhIHhtbG5zOng9ImFkb2JlOm5zOm1ldGEvIiB4OnhtcHRrPSJYTVAgQ29yZSA1LjQuMCI+IDxyZGY6UkRGIHhtbG5zOnJkZj0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zIyI+IDxyZGY6RGVz.......(image data here)");
//
//} catch (UnsupportedEncodingException exception) {
// Log.e("ERROR", "exception", exception);
// return null and don't pass any POST string if you encounter encoding error
//return null;
//}
return httpPostBody.getBytes();
}
// #Override
// public String getBody() throws AuthFailureError {
// image = getStringImage(bitmap);
// System.out.printf(image);
// String params= "";
// params= image;
// return params;
//
// }
// #Override
// protected Map<String, String> getParams() throws AuthFailureError {
// image = getStringImage(bitmap);
// System.out.printf(image);
// Map<String,String> params = new Hashtable<String, String>();
// params.put("", image);
// return params;
// }
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
return params;
}
};
//Creating a Request Queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
System.out.println(stringRequest);
}
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri filePath = data.getData();
try {
//Getting the Bitmap from Gallery
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
//Setting the Bitmap to ImageView
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void onClick(View v) {
if(v == buttonChoose){
showFileChooser();
}
if(v == buttonUpload){
try {
uploadImage();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public void postText(View v) {
try {
RequestQueue requestQueue = Volley.newRequestQueue(this);
String URL = "http://api.getquesto.com:8080/upload";
JSONObject jsonBody = new JSONObject();
jsonBody.put("Text:", "A leaf is an organ of a vascular plant and is the principal lateral appendage of the stem.[1] The leaves and stem together form the shoot.[2] Leaves are collectively referred to as foliage, as in \"autumn foliage.\"[3][4]\n" +
"\n" +
"\n" +
"Diagram of a simple leaf.\n" +
"Apex Midvein (Primary vein) Secondary vein. Lamina. Leaf margin Petiole Bud Stem\n" +
"Although leaves can be seen in many different textures and sizes, typically a leaf is a thin, dorsiventrally flattened organ, borne above ground and specialized for photosynthesis. In most leaves, the primary photosynthetic tissue, the (palisade mesophyll), is located on the upper side of the blade or lamina of the leaf[1] but in some species, including the mature foliage of Eucalyptus,[5] palisade mesophyll is present on both sides and the leaves are said to be isobilateral. Most leaves have distinctive upper (adaxial) and lower (abaxial) surfaces that differ in colour, hairiness, the number of stomata (pores that intake and output gases), epicuticular wax amount and structure and other features.\n" +
"\n" +
"Broad, flat leaves with complex venation are known as megaphylls and the species that bear them, the majority, as broad-leaved or megaphyllous plants. In others, such as the clubmosses, with different evolutionary origins, the leaves are simple, with only a single vein and are known as microphylls.[6]\n" +
"\n" +
"Some leaves, such as bulb scales are not above ground, and in many aquatic species the leaves are submerged in water. Succulent plants often have thick juicy leaves, but some leaves are without major photosynthetic function and may be dead at maturity, as in some cataphylls, and spines). Furthermore, several kinds of leaf-like structures found in vascular plants are not totally homologous with them. Examples include flattened plant stems called phylloclades and cladodes, and flattened leaf stems called phyllodes which differ from leaves both in their structure and origin.[4][7] Many structures of non-vascular plants, such as the phyllids of mosses and liverworts and even of some foliose lichens, which are not plants at all (in the sense of being members of the kingdom Plantae), look and function much like leaves.");
final String mRequestBody = jsonBody.toString();
String json = null;
StringRequest stringRequest = new StringRequest(POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.i("VOLLEY", response);
Toast.makeText(PostImage.this, response , Toast.LENGTH_LONG).show();
}
}, 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;
}
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("Content-Type","text/plain");
return params;
}
#Override
protected Response<String> parseNetworkResponse(NetworkResponse response) {
String responseString = "";
if (response != null) {
responseString = String.valueOf(response.statusCode);
// can get more details such as response.headers
}
return Response.success(responseString, HttpHeaderParser.parseCacheHeaders(response));
}
};
requestQueue.add(stringRequest);
} catch (JSONException e) {
e.printStackTrace();
}
}
}`
does anyone know how to make it send through data?

Uploading a File using Volley API via PUT method

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);

Send byte[] from android volley to asp.net mvc

I am trying to upload an image from android to asp.net mvc webapp. I've the following code to upload image on android part -
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
private String UPLOAD_URL ="UploadSignature?id=1";
private String KEY_IMAGE = "image";
private String KEY_NAME = "name";
private Bitmap bitmap;
private void uploadImage(){
StringRequest stringRequest = new StringRequest(Request.Method.POST, UPLOAD_URL,
new Response.Listener<String>() {
#Override
public void onResponse(String s) {
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
String image = getStringImage(bitmap);
String name = "firstImage";
Map<String,String> params = new Hashtable<String, String>();
params.put(KEY_IMAGE, image);
params.put(KEY_NAME, name);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
In asp.net mvc controller-
[HttpPost]
public ActionResult UploadSignatureTwo(byte[] Data)
{
System.IO.File.WriteAllBytes( #"D:\test.jpg", Data);
}
But it says Data can not be null.
Any help?

Categories

Resources