I am trying to write code to send jpg images to a server that can receive JSON requests. This images are stored on the device. I am basically porting a Python code that uses Requests: HTTP for Humans to communicate with a server. So far I managed to establish the communication with the code I pasted below. So I can see some hope.
// JAVA code on Android
String URL = BASE_URL + "/relative_url";
JsonObjectRequest postRequest = new JsonObjectRequest( Request.Method.POST, URL, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.i(TAG, "Successful POST request");
try {
sceneid = response.getInt("id");
Log.i(TAG, "Scene id: " + sceneid);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.i(TAG, "Bad POST request");
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
String credentials = "myuser:mypass";
String auth = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
headers.put("Authorization", auth);
return headers;
}
};
queue.add(postRequest);
However, I am not able to replicate the Python code below. I already checked thoroughly for a solution online, but I did not manage to make it work. The solutions I found either use deprecated libraries or the code does not work. The command in python I am trying to replicate is:
# Python code to replicate in JAVA
auth = {'myuser', 'mypass'}
file = {'jpgdata': open('myimg.jpg','rb')}
req = requests.post(BASE_URL + '/relative_url', params={'param', param}, files=file, auth=auth)
Some help will be really appreciated.
Thank you in advance.