In my app I want to decode raw address into coordinates. I do it like that:
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
try {
params.add("geocode", URLEncoder.encode(charSequence.toString(), "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
client.post(getApplicationContext(), "https://geocode-maps.yandex.ru/1.x/", params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
Log.d("Yandex Geocode", "Success! Answer = " + new String(responseBody));
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
Log.d("Yandex Geocode", "Failure :( Error = " + error.toString());
}
});
However, this request can't reach server.
failed to connect to geocode-maps.yandex.ru/213.180.204.122 (port 443) after 10000ms: isConnected failed: ECONNREFUSED (Connection refused)
Any suggestions why it't not working?
EDIT
It not working because yandex provides this api only for webapps and sites.
Found an ugly workaround for this. I'm loading a page in webview with this request url and getting raw text from response, from webview.
You can try with Android Geocoder. It is android native API.
A class for handling geocoding and reverse geocoding.
Related
I hava a express server to send data to and from the server for my mobile app.
this is what my express server sends back from my post request I send on my app to the server
then(() => { console.log("ok send"); res.status(200).send("ok")}).catch((err) => {console.log(err); res.status(400).send('error')})
The post request gets send and recieved by the server and I want te server to send an Ok response back to the app. It does this correct because I get an ok send in console. In the mobile app I use a AsyncHttpClient.
AsyncHttpClient.post("/url/" + id,json,new JsonHttpResponseHandler(){
#Override
public void onSuccess(int statusCode, Header[] headers, String response) {
super.onSuccess(statusCode, headers, response);
System.out.println("succes");
}
#Override
public void onFailure(int statuscode,Header[] headers, String response, Throwable trowable){
super.onFailure(statuscode,headers,response,trowable);
System.out.println("fail");
System.out.println(response);
System.out.println("statuscode = " + statuscode);
}
});
When I recieve the ok back it automatically goes to the onFailure even if statuscode = 200.
And android gives a semi error message:
W/JsonHttpRH: onFailure(int, Header[], String, Throwable) was not overriden, but callback was received
org.json.JSONException: Response cannot be parsed as JSON data
How would I be able to fix this problem and make it go to onsucces ?
thx
change JsonHttpResponseHandler to TextHttpResponseHandler
client.post("/url/" + id,json,new TextHttpResponseHandler(){
#Override
public void onSuccess(int statusCode, Header[] headers, String response) {
System.out.println("succes");
}
#Override
public void onFailure(int statuscode,Header[] headers, String response, Throwable trowable){
System.out.println("fail");
System.out.println(response);
System.out.println("statuscode = " + statuscode);
}
});
I have a node.js server running on localhost, and using an Android app I am trying to generate a client token with the code on the server; however, when using a AsyncHttpClient .get() method which creates a new TextHttpResponseHandler, neither the Success or Failed methods are called. I can open localhost:3000 in Chrome and I get the client token no worries, but no response on the Android app.
Node.js Server:
var braintree = require('braintree')
var express = require('express')
var app = express()
var gateway = braintree.connect({
accessToken: "access_token removed"
});
app.listen(3000);
app.get("/client_token", function (req, res) {
gateway.clientToken.generate({}, function (err, response) {
res.send(response.clientToken);
});
});
Android Code:
private void generateClientToken() {
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://localhost:3000/client_token", new TextHttpResponseHandler() {
#Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
Log.i(TAG, "onFailure: ");
}
#Override
public void onSuccess(int statusCode, Header[] headers, String responseString) {
Log.i(TAG, "onSuccess: ");
CLIENT_TOKEN = responseString;
}
});
}
I have tried using the runOnUIThread() method, but I get the same result.
To reiterate, neither functions are run, the logs are not executed and the client token variable is not changed when this method is run.
Any help appreciated!
Cheers!
I am trying to get make a post request in Android using AsyncHttpClient using this code:
JSONObject jsonParams=new JSONObject();
try {
jsonParams.put("email", email);
}
catch (Exception e){
}
try {
StringEntity entity = new StringEntity(jsonParams.toString());
AsyncHttpClient client = new AsyncHttpClient();
client.post(getApplicationContext(),URL,entity, "application/json", new AsyncHttpResponseHandler(){
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {}
});
I am trying to access this data sent in the post request in my Python server. However, whenever I do request.json in my Python server, I get 'None' as response.
I also tried request.get_json(force=True) but getting 404 error code.
I dont really know if the data is being sent by the client APP or I am making a mistake while trying to retrieve it at the server side. Please help me with this issue.
String content = new String(responseBody);
Log.e("SUCCESS_RESP",""+content);
I am trying to upload an image to a PHP file on a server using the POST method. I have been trying to do this using LoopJ AndroidAsyncHttp with no success. The server also requires a basic auth username and password. So far, I have been able to successfully POST the regular data parameters (These are simple string key-valued pairs like: "name":"joe") and get a response from the server. However, as soon as I try to attach the image to the POST request, the request fails giving me the following errors:
Error Message: null
Error Cause: org.apache.http.client.NonRepeatableRequestException: Cannot retry request with a non-repeatable request entity
The code that I am using follows the examples given at http://loopj.com/android-async-http/ very closely. Here is the code that I am using:
RequestParams params = new RequestParams();
params.put("name",name);
String path = "/path/to/img";
File myFile = new File(path, "picture.png");
if( myFile.exists() ) {
try {
params.put("picture", myFile);
} catch(FileNotFoundException e) {
Log.d("App","Error Attaching Picture: " + e.toString());
}
} else {
Log.d("App","File DOES NOT exist");
}
String urlString = "url-to-server";
AsyncHttpClient client = new AsyncHttpClient();
client.setBasicAuth("User", "Pass");
client.post(urlString, params, new AsyncHttpResponseHandler(){
#Override
public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
super.onSuccess(statusCode, headers, responseBody);
}
#Override
public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
super.onFailure(statusCode, headers, responseBody, error);
Log.d("App","Upload Failed!");
Log.d("App","Error Message: " + error.getMessage());
Log.d("App", "Error Cause: " + error.getCause());
}
#Override
public void onStart() {
super.onStart();
}
});
So what am I doing wrong here?
I have also double checked and the file that I am reading to get the image does exist and it does have data in it, so I have ruled that out as a potential cause.
I have been struggling with this issue a little too long now.
Thanks in advance to anyone who can help!
This was a bug in the old 1.4.4 version of AsyncHTTPClient. It can be fixed by updating to the 1.4.8 version. In your build.gradle file under the dependencies section it should look like this:
compile 'com.loopj.android:android-async-http:1.4.8'
i'm trying to upload an image via http post method from android device to laravel server. but Posting an image is not working, the post parameter (including image file) doesn't seem to be sent correctly.
i'm using Android Asynchronous Http Client (http://loopj.com/android-async-http/) to post an image from android. and here is the code :
Android :
RequestParams params = new RequestParams();
params.put("id_personil", session.getUID());
params.put("id_deskel", session.getDID());
params.put("jenis", jenisLap.getSelectedItemPosition());
params.put("judul", judul.getText().toString());
params.put("lokasi", lokasi.getText().toString());
params.put("uraian", uraian.getText().toString());
try{
for (int a =0; a<imageUrl.size();a++){
params.put("pic[]", new File(Environment.getExternalStorageDirectory().getPath()+imageUrl.get(0)));
}
}catch(FileNotFoundException e){e.printStackTrace();}
AsyncHttpClient client = new AsyncHttpClient();
client.post("http://10.0.3.2:8888/api/v1/lapgiat", params, new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
super.onSuccess(statusCode, headers, response);
ShowAlert(response.toString(), "text");
}
#Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
super.onFailure(statusCode, headers, throwable, errorResponse);
ShowAlert("Error", "error");
}
});
Laravel
if(Request::has('pic')){
$files = Input::file('pic');
//dd($files);
$det_pic = [];
foreach ($files as $file) {
$filename = rand(11111,99999).'.'.$file->getClientOriginalExtension();
$file->move('uploads', $filename);
$det_pic[] = ['id_lapgiat'=>$id, 'file'=>$filename];
}
DB::table('bah_det_lapgiat_photo')->insert($det_pic);
$output['has picture'] = true;
}
can anyone help me?
Check using cURL or POSTMAN client and see if it's working there. If not, you can use this sample code for laravel.
//Checks if request has file or not
if ($request->hasFile('pic')) {
//checks if file is uploaded or not
if ($request->file('pic')->isValid()) {
$extension = $request->file('pic')->getClientOriginalExtension();
$imageName = str_random(60);
$request->file('pic')->move(base_path() . 'file/save/location', $imageName.".".$extension);
}
}