File is not correctly uploaded using POST-request - java

I am trying to upload a .zip file from an Android phone using a POST-request. I found through some scouting through the forums okhttp which should make it quite easy.
The file that arrives at the server is a zip-file with the correct name, but there is no content in the file (it is 0kb). I suspect that the stream is not correctly flushed when sending by okhttp.
public class FileSender extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
String zipPath = params[0];
String zipName = params[1];
String serverUrl = "http://192.168.1.109:5000"+"/files/"+zipName;
File file = new File(zipPath+zipName);
Log.d("File name", "zipName: "+zipName+" file.getName(): "+file.getName());
// TODO file is not send properly...
RequestBody postBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart(zipName, file.getName(),
RequestBody.create(MediaType.parse("application/octet-stream"), file))
.build();
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(serverUrl)
.post(postBody)
// TODO insert API-key here
.addHeader("API-key", "<my-api-key>")
.build();
try {
Response response = client.newCall(request).execute();
} catch (IOException e) {
e.printStackTrace();
}
return "Request Submitted";
}}
I basically implemented it with this, this as template.
Am I doing something wrong? What is another way to upload files this way?
Using Insomnia I am able to send files and there the Content-Type is also "application/octet-stream".

I managed to make it work. The issue was on my Flask-server side. This is the code that accepts the file:
#api.route("/files", methods=["POST"])
def post_file():
"""Upload a file."""
zipfile = request.files["zip"]
filename = secure_filename(zipfile.filename)
# Check if user has correct key
user_key = request.headers.get("API-key")
if user_key not in ALLOWED_KEYS:
return f"Permission denied. Key '{user_key}' has no access.", 401
if "/" in filename:
# Return 400 BAD REQUEST
abort(400, "no subdirectories directories allowed")
zipfile.save(os.path.join(UPLOAD_DIRECTORY, filename))
# Before I tried this (which does not work):
# with open(os.path.join(UPLOAD_DIRECTORY, secure_filename(filename)), "wb") as fp:
# fp.write(request.data)
# Return 201 CREATED
return "Successfully uploaded file.", 201
Here the code of my Android side:
public class FileSender extends AsyncTask<String, Boolean, Boolean> {
#Override
protected Boolean doInBackground(String... params) {
String zipPath = params[0];
String zipName = params[1];
// TODO put ip in env-variable
String serverUrl = "http://IP:Port"+"/files";
File file = new File(zipPath+zipName);
Log.d("File name", "zipName: "+zipName+" file.getName(): "+file.getName());
RequestBody postBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("zip", file.getName(),
RequestBody.create(MediaType.parse("application/zip"), file))
.build();
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(serverUrl)
.post(postBody)
// TODO insert API-key here
.addHeader("API-key", "<API-Key>")
.build();
try {
Response response = client.newCall(request).execute();
Log.d("SendToServer", "Worked: "+response.body().string());
return true;
} catch (IOException e) {
Log.d("SendToServer", "Error: "+e.toString());
e.printStackTrace();
return false;
}
}
}

Related

Http Ok3 Returns two responses

I am connecting black box backend, I have no control over the source and cannot modify the backend, using Ok Http 3. But for some reason, I am getting two results and I don't know what's going on. I suspect two threads are becoming active. But I don't know how to stop it. I tried both Synchronous and Asynchronous connection to no effect. I am new to Ok Http 3, so I am not sure what I am doing wrong.
I/Results: {"TotalResultsCount":3,"Results":[{
I/Results: {"TotalResultsCount":24,"Results":[
Here's is my synchronous code
class CallBackendSync extends AsyncTask {
OkHttpClient client = new OkHttpClient();
JSONObject resultsObject = null;
#Override
protected Object doInBackground(Object [] objects) {
String searchTerm = (String) objects[0];
String url = (String) objects[1];
String token = (String) objects[2];
String results = "";
//Search Body
RequestBody searchBody = new FormBody.Builder()
.add("QueryText", searchTerm)
.add("Categories", "")
.add("ChargeOutPerMinuteFrom", "0")
.add("ChargeOutPerMinuteTo", "0")
.add("maxDistance", "0")
.add("longitude", "0")
.add("latitude", "0")
.add("page", "0")
.build();
//Create request
Request.Builder builder = new Request.Builder();
builder.url(url);
builder.addHeader("Accept", "application/json");
if (token != null) {
builder.addHeader("Authorization", token);
}
builder.post(searchBody);
Request request = builder.build();
try {
Response response = client.newCall(request).execute();
results = results + response.body().string();
resultsObject = new JSONObject(results);
Log.i("Results", results);
return resultsObject;
}catch (Exception e){
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String s){
super.onPostExecute(s);
displayResults(resultsObject);
}
}
I am calling the backend from MainActivity using the code fragment below
CallBackendSync sync = new CallBackendSync();
String [] params = {searchTerm, serverBaseUrl + url, accessToken};
sync.execute(params);
Any ideas about what's going wrong will be much appreciated.

How to write java web services to upload image from android and use it in android

I see almost all webservice for android are written in PHP code. With Java I found an example of a rest service to upload image. I coded follow that code but when run test on my android device and Advanced RESTClient of chorme, I get error: HTTP Status 500 - Internal Server Error: Servlet.init () for servlet [Jersey REST Service] threw exception.. My URL: "http://srv.triaxvn.com:8080/logisticwsm/file/image-upload"
In android I use code:
#Override
protected String doInBackground(Void... params) {
return uploadFile();
}
#SuppressWarnings("deprecation")
private String uploadFile() {
File sourceFile = new File(filePath);
String fileName = sourceFile.getName();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(FILE_UPLOAD_URL);
MultipartEntity entity = new MultipartEntity();
// Extra parameters if you want to pass to server
entity.addPart("fileDescription", new StringBody(""));
entity.addPart("fileName", new StringBody(fileName != null ? fileName : sourceFile.getName()));
// Adding file data to http body
FileBody fileBody = new FileBody(sourceFile, "application/octect-stream") ;
entity.addPart("attachment", fileBody);
//totalSize = entity.getContentLength();
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(r_entity);
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
}
My Restful web service code:
#Path("/file")
public class UploadFile {
private final String UPLOADED_FILE_PATH = "c:\\uploaded";
#POST
#Path("/image-upload")
#Consumes("multipart/form-data")
public Response uploadFile(MultipartFormDataInput input) throws IOException
{
//Get API input data
Map<String, List<InputPart>> uploadForm = input.getFormDataMap();
//Get file name
String fileName = uploadForm.get("fileName").get(0).getBodyAsString();
//Get file data to save
List<InputPart> inputParts = uploadForm.get("attachment");
for (InputPart inputPart : inputParts)
{
try
{
//Use this header for extra processing if required
#SuppressWarnings("unused")
MultivaluedMap<String, String> header = inputPart.getHeaders();
// convert the uploaded file to inputstream
InputStream inputStream = inputPart.getBody(InputStream.class, null);
byte[] bytes = IOUtils.toByteArray(inputStream);
// constructs upload file path
fileName = UPLOADED_FILE_PATH + fileName;
writeFile(bytes, fileName);
System.out.println("Success !!!!!");
}
catch (Exception e)
{
e.printStackTrace();
return Response.status(200).entity("Uploaded file name : "+e.getMessage()).build();
}
}
return Response.status(200)
.entity("Uploaded file name : "+ fileName).build();
}
//Utility method
private void writeFile(byte[] content, String filename) throws IOException
{
File file = new File(filename);
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream fop = new FileOutputStream(file);
fop.write(content);
fop.flush();
fop.close();
}
I do not know the error caused from by android code or Server Restful code and how to fix it

Upload File: Comsuming WCF Web Service Using Java

I have a WCF Web Service (.NET C#). And I want to consume that service by java client application.
I have a following code using that I am successfully able to connect with the Web Service. But now I am facing problem with uploadFile method.
When I am passing string to the request entity then it call the web service method but as I passed/set FileInputStream RequestEntity then it throw exception ...
Connection reset by peer: socket write error
My Java Client Code is as following....
Please ignore: logging is not added here...
public void consumeService(){
String sXML = null;
String sURI = URI + "/upload";
sXML = item;
HashMap<String, String> header = new HashMap();
header.put("Content-type", "application/x-www-form-urlencoded");
File file = new File("C:\\Users\\admin\\Desktop\\P1130503.JPG");
try {
RequestEntity requestEntity= new InputStreamRequestEntity(
new FileInputStream(sFile), InputStreamRequestEntity.CONTENT_LENGTH_AUTO);
for (Map.Entry<String, String> entry : headers.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
headers.addHeader(key, value);
}
} catch (Exception ex) {
Logger.getLogger(C3Service.class.getName()).log(Level.SEVERE, null, ex);
}
HttpMethodBase httpPostRequest = new PostMethod(url + buildParams());
HttpClient client = new HttpClient();
try {
// add headers
Iterator it = headers.entrySet().iterator();
while (it.hasNext()) {
Entry header = (Entry) it.next();
httpPostRequest.addRequestHeader((String) header.getKey(), (String) header.getValue());
}
((PostMethod) httpPostRequest).setRequestEntity(requestEntity);
try {
respCode = client.executeMethod(httpPostRequest);
System.out.println("Response Code "+respCode);
response = httpPostRequest.getResponseBodyAsString();
this.responsePhrase = httpPostRequest.getStatusText();
System.out.println("Response "+response);
System.out.println("Response Phase "+responsePhrase);
}catch(Exception ex){
System.out.println("ErrorS "+ex.toString());
} finally {
// resp.close();
httpPostRequest.releaseConnection();
}
}catch(Exception ex){
System.out.println("ErrorD "+ex.toString());
}
finally {
//client.c
}
}
NOTE: when I passed string and set StringRequestEntity then it working file.
new StringRequestEntity(statusAsXml, "text/plain", Constants.DEFAULT_ENCODING)
C# CODE
IService
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "upload")]
bool upload(Stream relativePath);
I got my answer. It was the matter of assigning valid content type. I was setting content type
header.put("Content-type", "application/x-www-form-urlencoded");
After using following content-type, I am able to upload file successfully
httpConn.setRequestProperty("Content-Type","multipart/form-data");

What's wrong I did to send a batch request to google?

I tried to send a batch request to Google with OkHttp, but I always received error 500 and Unknown Error in response.
This is my code, the token is get from GoogleAuthUtil.
MultipartBuilder multipartBuilder = new MultipartBuilder();
MediaType http = MediaType.parse("application/http");
MediaType mixed = MediaType.parse("multipart/mixed");
multipartBuilder.addPart(RequestBody.create(http, "GET https://www.googleapis.com/gmail/v1/users/me/messages"));
multipartBuilder.type(mixed);
Request request = new Request.Builder()
.url("https://www.googleapis.com/batch")
.header("Authorization", " Bearer " + token)
.post(multipartBuilder.build())
.build();
try{
Response response = client.newCall(request).execute();
String res = response.body().string();
}
catch (IOException e){
e.printStackTrace();
}
Finally, I solved this problem. All the code has no problem besides one line:
multipartBuilder.addPart(RequestBody.create(http, "GET https://www.googleapis.com/gmail/v1/users/me/messages"));
It should be convert to byte[] first and call the similar method later and do not forget the \n.
byte[] request = (https://www.googleapis.com/gmail/v1/users/me/messages).getBytes();
RequestBody partRequest = RequestBody.create(HTTP, request);
I find out the problem in the OkHttp source code.
public static RequestBody create(MediaType contentType, String content) {
Charset charset = Util.UTF_8;
if (contentType != null) {
charset = contentType.charset();
if (charset == null) {
charset = Util.UTF_8;
contentType = MediaType.parse(contentType + "; charset=utf-8");
}
}
byte[] bytes = content.getBytes(charset);
return create(contentType, bytes);
}
The problem is the charset to be added to Content-Type. It makes the 500 error.

how to use okhttp to upload a file?

I use okhttp to be my httpclient. I think it's a good api but the doc is not so detailed.
how to use it to make a http post request with file uploading?
public Multipart createMultiPart(File file){
Part part = (Part) new Part.Builder().contentType("").body(new File("1.png")).build();
//how to set part name?
Multipart m = new Multipart.Builder().addPart(part).build();
return m;
}
public String postWithFiles(String url,Multipart m) throws IOException{
ByteArrayOutputStream out = new ByteArrayOutputStream();
m.writeBodyTo(out)
;
Request.Body body = Request.Body.create(MediaType.parse("application/x-www-form-urlencoded"),
out.toByteArray());
Request req = new Request.Builder().url(url).post(body).build();
return client.newCall(req).execute().body().string();
}
my question is:
how to set part name? in the form, the file should be named file1.
how to add other fields in the form?
Here is a basic function that uses okhttp to upload a file and some arbitrary field (it literally simulates a regular HTML form submission)
Change the mime type to match your file (here I am assuming .csv) or make it a parameter to the function if you are going to upload different file types
public static Boolean uploadFile(String serverURL, File file) {
try {
RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("file", file.getName(),
RequestBody.create(MediaType.parse("text/csv"), file))
.addFormDataPart("some-field", "some-value")
.build();
Request request = new Request.Builder()
.url(serverURL)
.post(requestBody)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(final Call call, final IOException e) {
// Handle the error
}
#Override
public void onResponse(final Call call, final Response response) throws IOException {
if (!response.isSuccessful()) {
// Handle the error
}
// Upload successful
}
});
return true;
} catch (Exception ex) {
// Handle the error
}
return false;
}
Note: because it is async call, the boolean return type does not indicate successful upload but only that the request was submitted to okhttp queue.
Here's an answer that works with OkHttp 3.2.0:
public void upload(String url, File file) throws IOException {
OkHttpClient client = new OkHttpClient();
RequestBody formBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", file.getName(),
RequestBody.create(MediaType.parse("text/plain"), file))
.addFormDataPart("other_field", "other_field_value")
.build();
Request request = new Request.Builder().url(url).post(formBody).build();
Response response = client.newCall(request).execute();
}
Note: this answer is for okhttp 1.x/2.x. For 3.x, see this other answer.
The class Multipart from mimecraft encapsulates the whole HTTP body and can handle regular fields like so:
Multipart m = new Multipart.Builder()
.type(Multipart.Type.FORM)
.addPart(new Part.Builder()
.body("value")
.contentDisposition("form-data; name=\"non_file_field\"")
.build())
.addPart(new Part.Builder()
.contentType("text/csv")
.body(aFile)
.contentDisposition("form-data; name=\"file_field\"; filename=\"file1\"")
.build())
.build();
Take a look at examples of multipart/form-data encoding to get a sense of how you need to construct the parts.
Once you have a Multipart object, all that's left to do is specify the right Content-Type header and pass on the body bytes to the request.
Since you seem to be working with the v2.0 of the OkHttp API, which I don't have experience with, this is just guess code:
// You'll probably need to change the MediaType to use the Content-Type
// from the multipart object
Request.Body body = Request.Body.create(
MediaType.parse(m.getHeaders().get("Content-Type")),
out.toByteArray());
For OkHttp 1.5.4, here is a stripped down code I'm using which is adapted from a sample snippet:
OkHttpClient client = new OkHttpClient();
OutputStream out = null;
try {
URL url = new URL("http://www.example.com");
HttpURLConnection connection = client.open(url);
for (Map.Entry<String, String> entry : multipart.getHeaders().entrySet()) {
connection.addRequestProperty(entry.getKey(), entry.getValue());
}
connection.setRequestMethod("POST");
// Write the request.
out = connection.getOutputStream();
multipart.writeBodyTo(out);
out.close();
// Read the response.
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new IOException("Unexpected HTTP response: "
+ connection.getResponseCode() + " " + connection.getResponseMessage());
}
} finally {
// Clean up.
try {
if (out != null) out.close();
} catch (Exception e) {
}
}
I've created cool helper class for OkHttp3. it here
public class OkHttp3Helper {
public static final String TAG;
private static final okhttp3.OkHttpClient client;
static {
TAG = OkHttp3Helper.class.getSimpleName();
client = new okhttp3.OkHttpClient.Builder()
.readTimeout(7, TimeUnit.MINUTES)
.writeTimeout(7, TimeUnit.MINUTES)
.build();
}
private Context context;
public OkHttp3Helper(Context context) {
this.context = context;
}
/**
* <strong>Uses:</strong><br/>
* <p>
* {#code
* ArrayMap<String, String> formField = new ArrayMap<>();}
* <br/>
* {#code formField.put("key1", "value1");}<br/>
* {#code formField.put("key2", "value2");}<br/>
* {#code formField.put("key3", "value3");}<br/>
* <br/>
* {#code String response = helper.postToServer("http://www.example.com/", formField);}<br/>
* </p>
*
* #param url String
* #param formField android.support.v4.util.ArrayMap
* #return response from server in String format
* #throws Exception
*/
#NonNull
public String postToServer(#NonNull String url, #Nullable ArrayMap<String, String> formField)
throws Exception {
okhttp3.Request.Builder requestBuilder = new okhttp3.Request.Builder().url(url);
if (formField != null) {
okhttp3.FormBody.Builder formBodyBuilder = new okhttp3.FormBody.Builder();
for (Map.Entry<String, String> entry : formField.entrySet()) {
formBodyBuilder.add(entry.getKey(), entry.getValue());
}
requestBuilder.post(formBodyBuilder.build());
}
okhttp3.Request request = requestBuilder.build();
okhttp3.Response response = client.newCall(request).execute();
if (!response.isSuccessful()) {
throw new IOException(response.message());
}
return response.body().string();
}
/**
* <strong>Uses:</strong><br/>
* <p>
* {#code
* ArrayMap<String, String> formField = new ArrayMap<>();}
* <br/>
* {#code formField.put("key1", "value1");}<br/>
* {#code formField.put("key2", "value2");}<br/>
* {#code formField.put("key3", "value3");}<br/>
* <br/>
* {#code
* ArrayMap<String, File> filePart = new ArrayMap<>();}
* <br/>
* {#code filePart.put("key1", new File("pathname"));}<br/>
* {#code filePart.put("key2", new File("pathname"));}<br/>
* {#code filePart.put("key3", new File("pathname"));}<br/>
* <br/>
* {#code String response = helper.postToServer("http://www.example.com/", formField, filePart);}<br/>
* </p>
*
* #param url String
* #param formField android.support.v4.util.ArrayMap
* #param filePart android.support.v4.util.ArrayMap
* #return response from server in String format
* #throws Exception
*/
#NonNull
public String postMultiPartToServer(#NonNull String url,
#Nullable ArrayMap<String, String> formField,
#Nullable ArrayMap<String, File> filePart)
throws Exception {
okhttp3.Request.Builder requestBuilder = new okhttp3.Request.Builder().url(url);
if (formField != null || filePart != null) {
okhttp3.MultipartBody.Builder multipartBodyBuilder = new okhttp3.MultipartBody.Builder();
multipartBodyBuilder.setType(okhttp3.MultipartBody.FORM);
if (formField != null) {
for (Map.Entry<String, String> entry : formField.entrySet()) {
multipartBodyBuilder.addFormDataPart(entry.getKey(), entry.getValue());
}
}
if (filePart != null) {
for (Map.Entry<String, File> entry : filePart.entrySet()) {
File file = entry.getValue();
multipartBodyBuilder.addFormDataPart(
entry.getKey(),
file.getName(),
okhttp3.RequestBody.create(getMediaType(file.toURI()), file)
);
}
}
requestBuilder.post(multipartBodyBuilder.build());
}
okhttp3.Request request = requestBuilder.build();
okhttp3.Response response = client.newCall(request).execute();
if (!response.isSuccessful()) {
throw new IOException(response.message());
}
return response.body().string();
}
private okhttp3.MediaType getMediaType(URI uri1) {
Uri uri = Uri.parse(uri1.toString());
String mimeType;
if (uri.getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
ContentResolver cr = context.getContentResolver();
mimeType = cr.getType(uri);
} else {
String fileExtension = MimeTypeMap.getFileExtensionFromUrl(uri
.toString());
mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
fileExtension.toLowerCase());
}
return okhttp3.MediaType.parse(mimeType);
}
}
OkHttpClient client = new OkHttpClient.Builder().connectTimeout(10, TimeUnit.SECONDS).writeTimeout(180, TimeUnit.SECONDS).readTimeout(180, TimeUnit.SECONDS).build();
RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("File", path.getName(),RequestBody.create(MediaType.parse("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"),path))
.addFormDataPart("username", username)
.addFormDataPart("password", password)
.build();
Request request = new Request.Builder().url(url).post(body).build();
Response response = client.newCall(request).execute();
result = response.body().string();
Above code will send the username, password as the post parameter and the file will be uploaded in the name of "File".
PHP Server will receive the files
if (isset($_FILES["File"]) &&
isset($_POST['username']) &&
isset($_POST['password'])) {
//All Values found
}else{
echo 'please send the required data';
}
Perfect code for uploading any files to google drive along with metadata of files easily.
String url = String.format("https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart");
//String url = String.format("https://www.googleapis.com/upload/drive/v2/files?uploadType=resumable");
boolean status;
String metaDataFile = "{\"title\":\"" + step.getFile_name() + "\"," +
"\"description\":\"" + step.getDescription() + "\"," +
"\"parents\":[{\"id\":\"" + step.getFolderId() + "\"}]," +
"\"capabilities\":{\"canEdit\":\"" + false + "\", \"canDownload\":\" "+ false +" \" }, " +
"\"type\":\"" + step.getFile_access() + "\"" +
"}";
//get the encoded byte data for decode
byte[] file = Base64.decodeBase64(step.getFile_data());
//attaching metadata to our request object
RequestBody requestBodyMetaData = RequestBody.create(MediaType.parse("application/json"), metaDataFile);
//passing both meta data and file content for uploading
RequestBody requestBodyMultipart = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("metadata", null, requestBodyMetaData)
.addFormDataPart("file", null, RequestBody.create(MediaType.parse("application/octet-stream"), file))
.build();
Request request = new Request.Builder()
.url(url)
.addHeader("Authorization", String.format("Bearer %s", step.getAccess_token()))
.post(requestBodyMultipart)
.build();
OkHttpClient okHttpClient = new OkHttpClient();
try {
// Get response after rest call.
Response response = okHttpClient.newCall(request).execute();
status = response.code() == 200 ? true : false;
map.put(step.getOutput_variable(), response.code());
Asynchronously ...
public void UploadFileFromOkhttp(String filePath, String jwtToken){
String url = "https://api.baserow.io/api/user-files/upload-file/";
MultipartBody.Builder builder = new MultipartBody.Builder();
builder.setType(MultipartBody.FORM);
File file = new File(filePath);
builder.addFormDataPart("file" , file.getName() , RequestBody.create(MediaType.parse("image/*"), file));
RequestBody requestBody = builder.build();
Request request = new Request.Builder()
.url(url)
.addHeader("Authorization", "JWT "+ jwtToken)
.post(requestBody)
.build();
okHttpClient.newCall(request).enqueue(new okhttp3.Callback() {
#Override
public void onFailure(#NotNull Call call, #NotNull IOException e) {
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
OnError(e.getMessage());
}
});
}
#Override
public void onResponse(#NotNull Call call, #NotNull Response response) throws IOException {
final String responseData = response.body().string();
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
OnSuccess(responseData);
}
});
}
});
}

Categories

Resources