Loopj - Uploading Files with RequestParams c# .net - android

Trying to upload a file with params using loopj.
im trying to get file from Request.Files and params from Request.Form["create"]
but it is not uploading to the server.
Android Post method
try {
String createTeamURL = "http://url";
RequestParams params = new RequestParams();
params.put("file", new File(pathoffile));
params.add("create", regString);
AsyncHttpClient client = new AsyncHttpClient();
client.post(createTeamURL, params, new AsyncHttpResponseHandler() {
#Override
public void onStart() {
// called before request is started
}
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
// called when response HTTP status is "200 OK"
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
// called when response HTTP status is "4XX" (eg. 401, 403, 404)
}
#Override
public void onRetry(int retryNo) {
// called when request is retried
}
});
} catch (Exception e) {
Log.e("createTeamPreStep", e.getMessage());
}
My Web Api c# method
[HttpPost]
public async Task<string> CreateUHS()
{
var resultString = "";
foreach(HttpPostedFileBase s in Request.Files)
{
var a=s;
}
String sdf = Request.Form["create"];
}

You need to use put for string args.
please find the below both server and client methods.
and one more thing im really worried about your naming variable. its bad. please change it. Happy coding.
String createTeamURL = "http://url";
RequestParams params = new RequestParams();
params.put("file", new File(pathoffile));
params.put("create", regString);
Server (Web api)
[HttpPost]
public async Task<string> CreateUHS()
{
var file=Request.Files[0];
String otherArg = Request.Form["create"];
}

Related

Connection error node.js server . Http request in android showing host not reachable

I am using loopj library for http request, And i am using genymotion for testing. I also want to test on my mobile device but it is showing host unreachable on each ip, whenever i call onclick function on button click.
Here is the Code:
public void onClick(View view) {
username = emailET.getText().toString();
password = pwdET.getText().toString();
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
params.put("username", username);
params.put("password", password);
client.post("http://10.0.3.2:3000/index", params, new TextHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, String res) {
try {
JSONObject obj = new JSONObject(res);
if(obj.getString("success").equals("true")){
Toast.makeText(getApplicationContext(),"Service connected", Toast.LENGTH_LONG);
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(),"Server not connected",Toast.LENGTH_LONG);
}
// called when response HTTP status is "200 OK"
}
#Override
public void onFailure(int statusCode, Header[] headers, String res, Throwable t) {
// called when response HTTP status is "4XX" (eg. 401, 403, 404)
Toast.makeText(getApplicationContext(),"Bad Request",Toast.LENGTH_LONG);
}
}
);
Here are the snippet of node.js and mongodb server running:
node.js
Host unreachable error

AsyncHttpClient - POST request over HTTPS

I'm developing a new Android app which allow the user to rate the content. The rate is sent thanks to an asynchronous request (POST) over HTTPS. Unfortunately, the request don't reach my webservice. When I took a look at the log access log, the URL is truncated. You can find below the relevant code.
private static AsyncHttpClient getClient()
{
if(client == null)
{
client = new AsyncHttpClient(true, 80, 443);
client.getHttpClient().getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
client.getHttpClient().getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
}
return client;
}
public static void createComment(int idArticle, String content, final Context context, final Callback callback)
{
final User currentUser = RealmManager.getUser();
RequestParams paramsPost = new RequestParams();
paramsPost.put("id_article", idArticle);
paramsPost.put("id_utilisateur", currentUser.getId());
paramsPost.put("content", content);
HashMap<String, String> paramsGet = getDefaultParams(context, currentUser, "webservices.createCommentaire");
getClient().post(createGetURL(currentUser.getURL(), paramsGet), paramsPost, new AsyncHttpResponseHandler()
{
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] response)
{
callback.onSuccess(/*..*/);
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e)
{
callback.onFailure(/*..*/);
}
});
}
When I put a breakpoint and examine the request, it looks like :
https://api.webservices.com/index.php?option=webservices&app_version=2.0&task=createCommentaire&token=XXXXXXXXXXXX&version=v2&format=raw
But, in the access log, the URL is truncated after "?" :
POST - https://api.webservices.com/index.php?
Consequently, I got in the response the HTML of the index.php which I can't parse in JSON.
Thank you in advance for your help.
I have two suggestion for you.
Use from UrlEncoder.encode("") method for every part of your parameters
Do not use query string parameters for post data to server.

Android able to fetch google.com , but not any other webpage

I am using android-async-http to run a simple push notification example.
The device is able to receive the notification just fine. After it receives the file, I am calling a get request using the above mentioned library:
Log.d("TAG", "GOT");
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://mysafeinfo.com/api/data?list=states&format=json", new AsyncHttpResponseHandler() {
#Override
public void onStart() {
// called before request is started
}
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] response) {
// called when response HTTP status is "200 OK"
try {
String decoded = new String(response, "UTF-8");
Log.d("TAG", decoded);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] errorResponse, Throwable e) {
// called when response HTTP status is "4XX" (eg. 401, 403, 404)
try {
String dec = new String(errorResponse, "UTF-8");
Log.d("TAG",dec);
}
catch (UnsupportedEncodingException q){
q.printStackTrace();
}
}
#Override
public void onRetry(int retryNo) {
// called when request is retried
}
});
In that url should return json, but in my log, I see no messages at all. its all blank, that log.d is never called. But when I change that url to www.google.com, it returns some html (which is google's homepage) .
I have added
<uses-permission android:name="android.permission.INTERNET" />
to the manifest.
This is my logcat:
02-13 21:06:12.189
12101-12101/com.example.harshvardhangupta.gcmpleasework D/TAG: GOT
02-13 21:06:12.468
12101-12101/com.example.harshvardhangupta.gcmpleasework V/AsyncHttpRH:
Progress 1310 from 1522 (86%) 02-13 21:06:12.468
12101-12101/com.example.harshvardhangupta.gcmpleasework V/AsyncHttpRH:
Progress 3333 from 1522 (219%) 02-13 21:06:12.469
12101-12101/com.example.harshvardhangupta.gcmpleasework V/AsyncHttpRH:
Progress 5238 from 1522 (344%)
Do notice the dotted lines. After #Taylor Courtney's comment, I noticed that the response is coming , but its not being converted to a string from byte array properly
Well, Your AsyncHttpClient (doc) is requesting link which is returning JsonArray (response). You should use then JsonHttpResponseHandler (doc) instead.
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://mysafeinfo.com/api/data?list=states&format=json", new JsonHttpResponseHandler("UTF-8") {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
super.onSuccess(statusCode, headers, response);
Log.d(TAG, "onSuccess response: " + response.toString());
}
}
});

LoopJ AndroidAsyncHttp didn't go to onSuccess() or onFailure()

I used LoopJ AndroidAsyncHttp to get the response from the url, but the code didn't go into onSuccess() or onFailure(). The code is as below:
public void queryTopic(RequestParams params) {
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://192.168.0.109:8080/PhoneServer/topic/query", params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
System.out.println("It's in onSuccess");
}
// When the response returned by REST has Http response code
// other than '200'
#Override
public void onFailure(int statusCode, Throwable error,
String content) {
System.out.println("It's in onFailure");
}
});
System.out.println("It's over");
}
It just printed out the "It's over". What's the matter with the AsyncHttpClient?
How are you calling this? Is the context alive? If you are calling it from some place where context is no more available, then you will never get this callbacks.
I think you should try calling this queryTopic() method on click of some button and then wait for some time, you should get the response.
maybe the problem is that you ask to the server for a String
public void onSuccess(String response){...}
but server answer with a JSONObject
You can try this code:
AsyncHttpClient client = new AsyncHttpClient();
client.setTimeout(5000);
client.get(yourActivity.class, yourLink, new JsonHttpResponseHandler(){
#Override
public void onStart() {
Log.e(TAG, "start");
}
#Override
public void onSuccess(int status, Header[] headers, JSONObject answer) {
Log.e(TAG, "SUCCESS");
Log.e(TAG, "print => "+answer.getString("answer_id")); //"answer_id" is a random example
}
#Override
public void onFailure(int status, Header[] headers, String answer, Throwable throwable) {
Log.e(TAG, "FAILURE");
}
});
onSuccess() is an overloaded method be careful regarding what you send from server,
if it is a jsonObject or jsonArray or simple string. Use corresponding overloaded method of onSuccess(). I am using it too for a jsonObject response and i confront no error or irregularities in the method.
I return jsonObject from server for which my code works as expected and is as follows:
RequestParams params = new RequestParams();
params.put("pet","Cat");
params.put("name","Maran");
RestClient.get("/savelocation", params, new JsonHttpResponseHandler(){
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
Toast.makeText(context,response.toString(),Toast.LENGTH_SHORT).show();
Log.e("Error makerequest","request completed");
}
#Override
public void onFinish() {
//onLoginSuccess();
}
#Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable,JSONObject errorResponse){
Toast.makeText(context,throwable.toString(),Toast.LENGTH_LONG).show();
}
});
Note: RestClient is a static instance of AsyncHttpClient

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