AsyncHttpClient POST params become null on server - android

I am writing method to insert a new record to DB from android.
On client (android studio), I use AsyncHttpClient POST:
JSONObject params = new JSONObject();
try {
params.put("idOrd", idOrd);
params.put("idLan", aIdLan);
params.put("dbIP", dbIP);
params.put("dbName", dbName);
params.put("dbUsername", dbUsername);
params.put("dbPassword", Utility.dbEncrypt(dbPassword));
wsEditMaster(params);
} catch (JSONException | UnsupportedEncodingException e) {
e.printStackTrace();
}
public void wsEditMaster(final JSONObject params) throws UnsupportedEncodingException {
ByteArrayEntity entity = new ByteArrayEntity(params.toString().getBytes("UTF-8"));
entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded"));
client.post(this, "http://" + serverIP + "/DHD/general/editorder", entity, "application/x-www-form-urlencoded", new AsyncHttpResponseHandler() {
And on server (eclipse):
// HTTP Post Method
#POST
// Path: http://localhost/<appln-folder-name>/general/editorder
#Path("/editorder")
// Produces JSON as response
#Produces(MediaType.APPLICATION_JSON)
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
// Query parameters are parameters:
public String editOrder(#FormParam("idOrd") String idOrd,
#FormParam("idLan") String idLan, #FormParam("dbIP") String dbIP,
#FormParam("dbName") String dbName,
#FormParam("dbUsername") String dbUsername,
#FormParam("dbPassword") String dbPassword) throws Exception {
String response = "";
if (DBConnection.editOrder(idOrd, idLan, dbIP, dbName, dbUsername, dbPassword)) {
response = Utility.constructJSON("editOrder", true);
} else {
response = Utility.constructJSON("editOrder", false,
"Cannot insert to database!");
}
return response;
}
Everything works fine when I use GET, but when I use POST, all params became null in "editOrder" function.
Please help, thank you.

OK, I solved my problem. Simply, use RequestParams instead of JSONObject:
public void wsEditMaster(final RequestParams params) {
client.post("http://" + serverIP + "/DHD/general/editorder", params, new AsyncHttpResponseHandler() {

Related

I/O error: class path resource [] cannot be resolved to URL because it does not exist;

org.springframework.web.client.ResourceAccessException: I/O error: class path resource [storage/emulated/0/DCIM/Camera/IMG_20190130_135103614.jpg] cannot be resolved to URL because it does not exist; nested exception is java.io.FileNotFoundException: class path resource [storage/emulated/0/DCIM/Camera/IMG_20190130_135103614.jpg] cannot be resolved to URL because it does not exist.
I am getting this error while trying to upload an image from the gallery.
the same code works when the image is uploaded from the drawable folder.
#Override
protected void onPreExecute() {
showLoadingProgressDialog();
Resource resource = new ClassPathResource(file.getPath());
formData = new LinkedMultiValueMap<String, Object>(); "jpg");
formData.add("description", "image");
formData.add("file", resource);
}
#Override
protected String doInBackground(Void... params) {
try {
// The URL for making the POST request
final String url = getString(R.string.base_uri) + "/***";
HttpHeaders requestHeaders = new HttpHeaders();
// Sending multipart/form-data
requestHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
// Populate the MultiValueMap being serialized and headers in an HttpEntity object to use for the request
HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<MultiValueMap<String, Object>>(
formData, requestHeaders);
// Create a new RestTemplate instance
RestTemplate restTemplate = new RestTemplate(true);
// Make the network request, posting the message, expecting a String in response from the server
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, requestEntity,
String.class);
// Return the response body to display to the user
return response.getBody();
} catch (Exception e) {
Log.e(TAG, e.getMessage(), e);
}
return null;
}
server side code is
#RequestMapping(value = "/*", method = RequestMethod.POST, headers =
"Content-Type=multipart/form-data")
public #ResponseBody String
handleFormUpload(#RequestParam("description") String description,
#RequestParam("file") MultipartFile file) {
if (!file.isEmpty()) {
byte[] bytes = null;
try {
bytes = file.getBytes();
} catch (IOException e) {
System.out.println("error processing uploaded file");
}
return "file upload received! Name:[" + description + "] Size:["
+ bytes.length + "]";
} else {
return "file upload failed!";
}
}

Android: file extension is undefined in the response body after uploading a file to server

I am using the following code for sending files (pdf,docx,pptx etc) from user to user in a chatting application.
public class UploadFile extends AsyncTask<String, Void, String> {
protected MessageModel mMessage;
File file ;
String mimeType = "";
public UploadFile(MessageModel msg, File file) {
super();
this.mMessage = msg;
this.file = file;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String responseBodyText = null;
mimeType = mMessage.getMsgFileType();
MediaType MEDIA_TYPE = okhttp3.MediaType.parse(mimeType);
OkHttpClient client = new OkHttpClient();
try {
RequestBody req = new okhttp3.MultipartBody.Builder()
.setType(okhttp3.MultipartBody.FORM)
.addFormDataPart("chatFileUpload", file.getName(), RequestBody.create(MEDIA_TYPE, file)).build();
Request request = new Request.Builder()
.header("Authorization", "Bearer "+Constants.AUTH_TOKEN)
.addHeader("User-Agent", Constants.USER_AGENT)
.url(urlforFileUpload)
.post(req)
.build();
Response response = null;
response = client.newCall(request).execute();
if (!response.isSuccessful()) {
throw new IOException("Okhttp Error: " + response);
} else {
responseBodyText = response.body().string();
Log.d("PrintResponseBody", responseBodyText); // Print the response body here
}
} catch (IOException e) {
e.printStackTrace();
}
return responseBodyText;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
JSONObject msgFiles = new JSONObject();
if (result != null) {
try {
JSONObject responseObject = new JSONObject(result);
msgFiles.put("filename", responseObject.get("fileName"));
msgFiles.put("mimetype", responseObject.get("mimetype"));
msgFiles.put("filepath", responseObject.get("fileUploadPath"));
Log.d("PrintFileUploadPath", String.valueOf(responseObject.get("fileUploadPath")));
// Print the response upload file path with file name and extension;
//.... do other stuffs....
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
In the logcat, I'm getting extension as 'undefined' instead of proper extension name (.docx, .pptx etc). Can someone tell me which might cause this kind of behavior? Is it appropriate? If yes, how am I supposed to check which type of file user is receiving from server response?
An example of response I'm getting using debugger:
{
"status":"true",
"fileName":"1490691261587.undefined",
"fileUploadPath":"/uploads/chat_upload/1490691261587.undefined",
"mimetype":"file/file",
"msg":"File is uploaded successfully",
"downloadLink":"<a target=\"_blank\" href=\"/uploads/chat_upload/1490691261587.undefined\">New-Text-Document.txt909.txt</a>"
}
Thanks in advance.

How to send SMS using Twilio in my android application?

In my android application I have created one button, when I had pressed on the button I want to send message.So for that I have created one java class and written twilio code.
final TwilioRestClient client = new TwilioRestClient(
ACCOUNT_SID, AUTH_TOKEN);
// Get the main account (The one we used to authenticate the
// client)
final Account mainAccount = client.getAccount();
final SmsFactory messageFactory = mainAccount.getSmsFactory();
final Map<String, String> messageParams = new HashMap<String, String>();
messageParams.put("To", "+912342423423");
messageParams.put("From", "+132432432434");
messageParams.put("Body", "This is my message");
try {
messageFactory.create(messageParams);
} catch (TwilioRestException e) {
e.printStackTrace();
}
when I am using the above code it showing some error like java.lang.NoSuchMethodError: org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager
I have added only one jar file in lib folder as " twilio-java-sdk-3.3.10-jar-with-dependencies.jar ".
please tell me what can I do?
I have used HttpPost method to send sms in that i have passed my url with base authentication here is my code
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"https://api.twilio.com/2010-04-01/Accounts/{ACCOUNT_SID}/SMS/Messages");
String base64EncodedCredentials = "Basic "
+ Base64.encodeToString(
(ACCOUNT_SID + ":" + AUTH_TOKEN).getBytes(),
Base64.NO_WRAP);
httppost.setHeader("Authorization",
base64EncodedCredentials);
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("From",
"+123424353534"));
nameValuePairs.add(new BasicNameValuePair("To",
"+914342423434"));
nameValuePairs.add(new BasicNameValuePair("Body",
"Welcome to Twilio"));
httppost.setEntity(new UrlEncodedFormEntity(
nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
System.out.println("Entity post is: "
+ EntityUtils.toString(entity));
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
}
It is working well.
This solution with Retrofit
public static final String ACCOUNT_SID = "accountSId";
public static final String AUTH_TOKEN = "authToken";
private void sendMessage() {
String body = "Hello test";
String from = "+...";
String to = "+...";
String base64EncodedCredentials = "Basic " + Base64.encodeToString(
(ACCOUNT_SID + ":" + AUTH_TOKEN).getBytes(), Base64.NO_WRAP
);
Map<String, String> data = new HashMap<>();
data.put("From", from);
data.put("To", to);
data.put("Body", body);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://api.twilio.com/2010-04-01/")
.build();
TwilioApi api = retrofit.create(TwilioApi.class);
api.sendMessage(ACCOUNT_SID, base64EncodedCredentials, data).enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) Log.d("TAG", "onResponse->success");
else Log.d("TAG", "onResponse->failure");
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.d("TAG", "onFailure");
}
});
}
interface TwilioApi {
#FormUrlEncoded
#POST("Accounts/{ACCOUNT_SID}/SMS/Messages")
Call<ResponseBody> sendMessage(
#Path("ACCOUNT_SID") String accountSId,
#Header("Authorization") String signature,
#FieldMap Map<String, String> metadata
);
}
Dependencies for build.gradle
compile 'com.squareup.retrofit2:retrofit:2.1.0'
My method, using OkHttp:
1. Prerequisites
Gradle:
dependencies {
compile 'com.squareup.okhttp3:okhttp:3.4.1'
}
Manifest:
<uses-permission android:name="android.permission.INTERNET"/>
Permission in activity:
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.setThreadPolicy( new StrictMode.ThreadPolicy.Builder().permitAll().build() );
}
2. Code
private void sendSms(String toPhoneNumber, String message){
OkHttpClient client = new OkHttpClient();
String url = "https://api.twilio.com/2010-04-01/Accounts/"+ACCOUNT_SID+"/SMS/Messages";
String base64EncodedCredentials = "Basic " + Base64.encodeToString((ACCOUNT_SID + ":" + AUTH_TOKEN).getBytes(), Base64.NO_WRAP);
RequestBody body = new FormBody.Builder()
.add("From", fromPhoneNumber)
.add("To", toPhoneNumber)
.add("Body", message)
.build();
Request request = new Request.Builder()
.url(url)
.post(body)
.header("Authorization", base64EncodedCredentials)
.build();
try {
Response response = client.newCall(request).execute();
Log.d(TAG, "sendSms: "+ response.body().string());
} catch (IOException e) { e.printStackTrace(); }
}
I used Allu code for generathing authorization in header
Twilio Java SDK has third party dependencies without them it is not going to work. The dependencies are:
1. Httpcore
2. Httpclient
3. Commons lang
4. Json simple
5. Jackson
Not quite sure if you need them all, but at least now you are missing httpcore
You should use the BasicPhone project of Twilio SDK. I've tried this to call and now I can call too. This project has all the methods and functions that you need to call and to send SMS. First of all, you need a PHP web service to get capability token and pass that PHP script into your app.
This is how I solved my need.
public class TwilioAsyncTask extends AsyncTask {
Context context;
ProgressDialog progressDialog;
public TwilioAsyncTask(Context context) {
this.context = context;
}
#Override
protected String doInBackground(String... strings) {
//
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"https://api.twilio.com/2010-04-01/Accounts/AC_yourACCOUNT_SID_9b/SMS/Messages");
String base64EncodedCredentials = "Basic "
+ Base64.encodeToString(
(ACCOUNT_SID + ":" + AUTH_TOKEN).getBytes(),
Base64.NO_WRAP);
httppost.setHeader("Authorization",
base64EncodedCredentials);
try {
int randomPIN = (int) (Math.random() * 9000) + 1000;
String randomVeriValue = "" + randomPIN;
// these are for control in other anctivity used sharepreference
editorTwilio.putString("twilio_veri_no", randomVeriValue);
editorTwilio.commit();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("From",
"+148******")); // what number they gave you
nameValuePairs.add(new BasicNameValuePair("To",
"+90" + phoneNo)); // your phone or our customers
nameValuePairs.add(new BasicNameValuePair("Body",
"Your verification number is : " + randomVeriValue));
httppost.setEntity(new UrlEncodedFormEntity(
nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
System.out.println("Entity post is: "
+ EntityUtils.toString(entity));
// Util.showMessage(mParentAct, "Welcome");
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
//
return "Executed";
}
#Override
protected void onPostExecute(String result) {
// execution of result of Long time consuming operation
//progressDialog.dismiss();
}
#Override
protected void onPreExecute() {
progressDialog = ProgressDialog.show(context, "", " Wait for ");
}
#Override
protected void onProgressUpdate(String... text) {
// Things to be done while execution of long running operation is in
// progress. For example updating ProgessDialog
}
}
And call your Task
TwilioAsyncTask task = new TwilioAsyncTask(CountryAndPhone.this);
task.execute();

Android Volley - BasicNetwork.performRequest: Unexpected response code 400

Problem statement:
I am trying to access an REST API that will return a JSON object for various HTTP status codes (400, 403, 200 etc) using Volley.
For any HTTP status other than 200, it seems the 'Unexpected response code 400' is a problem. Does anyone have a way to bypass this 'error'?
Code:
protected void getLogin() {
final String mURL = "https://somesite.com/api/login";
EditText username = (EditText) findViewById(R.id.username);
EditText password = (EditText) findViewById(R.id.password);
// Post params to be sent to the server
HashMap<String, String> params = new HashMap<String, String>();
params.put("username", username.getText().toString());
params.put("password", password.getText().toString());
JsonObjectRequest req = new JsonObjectRequest(mURL, new JSONObject(
params), new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject obj = response
.getJSONObject("some_json_obj");
Log.w("myApp",
"status code..." + obj.getString("name"));
// VolleyLog.v("Response:%n %s", response.toString(4));
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.w("error in response", "Error: " + error.getMessage());
}
});
// add the request object to the queue to be executed
AppController.getInstance().addToRequestQueue(req);
}
One way of doing this without changing Volley's source code is to check for the response data in the VolleyError and parse it your self.
As of f605da3 commit, Volley throws a ServerError exception that contains the raw network response.
So you can do something similar to this in your error listener:
/* import com.android.volley.toolbox.HttpHeaderParser; */
public void onErrorResponse(VolleyError error) {
// As of f605da3 the following should work
NetworkResponse response = error.networkResponse;
if (error instanceof ServerError && response != null) {
try {
String res = new String(response.data,
HttpHeaderParser.parseCharset(response.headers, "utf-8"));
// Now you can use any deserializer to make sense of data
JSONObject obj = new JSONObject(res);
} catch (UnsupportedEncodingException e1) {
// Couldn't properly decode data to string
e1.printStackTrace();
} catch (JSONException e2) {
// returned data is not JSONObject?
e2.printStackTrace();
}
}
}
For future, if Volley changes, one can follow the above approach where you need to check the VolleyError for raw data that has been sent by the server and parse it.
I hope that they implement that TODO mentioned in the source file.
#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;
}
You need to add Content-Type to the header.
Me too got the same error but in my case I was calling url with blank spaces.
Then, I fixed it by parsing like below.
String url = "Your URL Link";
url = url.replaceAll(" ", "%20");
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new com.android.volley.Response.Listener<String>() {
#Override
public void onResponse(String response) {
...
...
...
Try this ...
StringRequest sr = new StringRequest(type,url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// valid response
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// error
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("username", username);
params.put("password", password);
params.put("grant_type", "password");
return params;
}
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
// Removed this line if you dont need it or Use application/json
// params.put("Content-Type", "application/x-www-form-urlencoded");
return params;
}
You mean that want to get status codes?
VolleyError has a member variable type of NetworkResponse and it is public.
You can access error.networkResponse.statusCode for http error code.
I hope it is helpful for you.
What I did was append an extra '/' to my url, e.g.:
String url = "http://www.google.com"
to
String url = "http://www.google.com/"
in my case, I was not writing reg_url with :8080 .
String reg_url = "http://192.168.29.163:8080/register.php";
change
public static final String URL = "http://api-Location";
to
public static final String URL = "https://api-Location"
it's happen because i'm using 000webhostapp app
Just to update all, after some deliberations, I have decided to use Async Http Client instead to solve my earlier problem. The library allows a cleaner approach (to me) to manipulate HTTP responses especially in cases where JSON objects are returned in all scenarios/HTTP statuses.
protected void getLogin() {
EditText username = (EditText) findViewById(R.id.username);
EditText password = (EditText) findViewById(R.id.password);
RequestParams params = new RequestParams();
params.put("username", username.getText().toString());
params.put("password", password.getText().toString());
RestClient.post(getHost() + "api/v1/auth/login", params,
new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers,
JSONObject response) {
try {
//process JSONObject obj
Log.w("myapp","success status code..." + statusCode);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onFailure(int statusCode, Header[] headers,
Throwable throwable, JSONObject errorResponse) {
Log.w("myapp", "failure status code..." + statusCode);
try {
//process JSONObject obj
Log.w("myapp", "error ..." + errorResponse.getString("message").toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}

POSTing JSON/XML using android-async-http (loopj)

I am using android-async-http and really liking it. I've run into a problem with POSTing data. I have to post data to the API in the following format: -
<request>
<notes>Test api support</notes>
<hours>3</hours>
<project_id type="integer">3</project_id>
<task_id type="integer">14</task_id>
<spent_at type="date">Tue, 17 Oct 2006</spent_at>
</request>
As per the documentation, I tried doing it using RequestParams, but it is failing. Is this any other way to do it? I can POST equivalent JSON too. Any ideas?
Loopj POST examples - extended from their Twitter example:
private static AsyncHttpClient client = new AsyncHttpClient();
To post normally via RequestParams:
RequestParams params = new RequestParams();
params.put("notes", "Test api support");
client.post(restApiUrl, params, responseHandler);
To post JSON:
JSONObject jsonParams = new JSONObject();
jsonParams.put("notes", "Test api support");
StringEntity entity = new StringEntity(jsonParams.toString());
client.post(context, restApiUrl, entity, "application/json",
responseHandler);
#Timothy answer did not work for me.
I defined the Content-Type of the StringEntity to make it work:
JSONObject jsonParams = new JSONObject();
jsonParams.put("notes", "Test api support");
StringEntity entity = new StringEntity(jsonParams.toString());
entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
client.post(context, restApiUrl, entity, "application/json", responseHandler);
Good Luck :)
a better way to post json
RequestParams params = new RequestParams();
params.put("id", propertyID);
params.put("lt", newPoint.latitude);
params.put("lg", newPoint.longitude);
params.setUseJsonStreamer(true);
ScaanRestClient restClient = new ScaanRestClient(getApplicationContext());
restClient.post("/api-builtin/properties/v1.0/edit/location/", params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
}
});
To post XML
protected void makePost() {
AsyncHttpClient client = new AsyncHttpClient();
Context context = this.getApplicationContext();
String url = URL_String;
String xml = XML-String;
HttpEntity entity;
try {
entity = new StringEntity(xml, "UTF-8");
} catch (IllegalArgumentException e) {
Log.d("HTTP", "StringEntity: IllegalArgumentException");
return;
} catch (UnsupportedEncodingException e) {
Log.d("HTTP", "StringEntity: UnsupportedEncodingException");
return;
}
String contentType = "string/xml;UTF-8";
Log.d("HTTP", "Post...");
client.post( context, url, entity, contentType, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
Log.d("HTTP", "onSuccess: " + response);
}
... other handlers
});
}
just write your xml or json to a string and send to server, with proper headers or without. and yes set "Content-Type" to "application/json"
If someone have a problem that httpclient send as Content-Type: text/plain, please refer this link: https://stackoverflow.com/a/26425401/361100
The loopj httpclient is somewhat changed (or has problem) which cannot override StringEntity native Content-Type to application/json.
You can add the JSON string as an InputStream of some kind - I've used the ByteArrayStream, then passing it to the RequestParams you should set the correctMimeType
InputStream stream = new ByteArrayInputStream(jsonParams.toString().getBytes(Charset.forName("UTF-8")));
multiPartEntity.put("model", stream, "parameters", Constants.MIME_TYPE_JSON);
Just make JSONObject and then convert it to String "someData" and simply send with "ByteArrayEntity"
private static AsyncHttpClient client = new AsyncHttpClient();
String someData;
ByteArrayEntity be = new ByteArrayEntity(someData.toString().getBytes());
client.post(context, url, be, "application/json", responseHandler);
It is working fine for me.
To post xml file to a php server :
public class MainActivity extends AppCompatActivity {
/**
* Send xml file to server via asynchttpclient lib
*/
Button button;
String url = "http://xxx/index.php";
String filePath = Environment.getExternalStorageDirectory()+"/Download/testUpload.xml";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
postFile();
}
});
}
public void postFile(){
Log.i("xml","Sending... ");
RequestParams params = new RequestParams();
try {
params.put("key",new File(filePath));
}catch (FileNotFoundException e){
e.printStackTrace();
}
AsyncHttpClient client = new AsyncHttpClient();
client.post(url, params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int i, cz.msebera.android.httpclient.Header[] headers, byte[] bytes) {
Log.i("xml","StatusCode : "+i);
}
#Override
public void onFailure(int i, cz.msebera.android.httpclient.Header[] headers, byte[] bytes, Throwable throwable) {
Log.i("xml","Sending failed");
}
#Override
public void onProgress(long bytesWritten, long totalSize) {
Log.i("xml","Progress : "+bytesWritten);
}
});
}
}
After adding android-async-http-1.4.9.jar to android studio,
go to build.gradle and add :
compile 'com.loopj.android:android-async-http:1.4.9' under dependencies
And on AndroidManifest.xml add:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Categories

Resources