I'm trying to connect means AsyncHttpClient to a php script on my website. The script do the html parsing of another page, and convert the result to json. it work well. But, when I try to take the json form java for using it on android, the method that have the only work of open a stream and return 'response', doesn't run onSuccess and onFailure both. can anyone help me?
Here the code:
private String getStream() {
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://jem88.net/eventsAroundYouParser.php", new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
System.out.println("response is here..."+response);
Log.d("eventstaker", "into response!!");
}
#Override
public void onFailure(Throwable e, String response) {
Log.d("eventstaker", "onFailure method is run... :(");
}
});
return "";
}`
I've set the internet and network_access permission in the manifest.
Thank you in advance
You can override more onFailure methods
Related
I have an arduino project, where i was able to set up an esp8266 as a webserver, and i am able to send data to it, eg. if i put "http://192.168.4.1/get?data=010" into the browser, it works perfectly.
I want to send data using an android app, which pretty much means using the above mentioned url, just with different values for "data".
I've tried using okhttp3, but it doesn't work.
Here is what I've tried:
public void sendMessage(View view) throws IOException {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("http://192.168.4.1/get?data=010")
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
public void onResponse(Call call, Response response)
throws IOException {
System.out.println(response.toString());
}
public void onFailure(Call call, IOException e) {
System.out.println("Failed");
}
});
}
This seems to work, with other apis, eg. if i put in https://reqres.in/api/users?page=2 as the url I get a response, but when i try to connect to the arduino, it doesn't do anything.
Adding android:usesClearTextTraffic="true" to the AndroidManifest.xml file solved the issue.
Thanks for the answer blackapps.
i could not found codes. I want to this;
for example
JSONObject result = function("url",paramsArrayList);
txt.setText(result.getString["result1"]);
i want to use so basic, please help me, what should i use? Thanks...
To send and receive data from php, you need to implement HTTP client in android side. I would strongly recommed you to use Retrofit, A type-safe HTTP client for Android and Java.
http://square.github.io/retrofit/
//delcare API interface
public interface TaskService {
#GET("/tasks")
Call<List<Task>> getTasks();
}
//Asynchronous Request
TaskService taskService = ServiceGenerator.createService(TaskService.class);
Call<List<Task>> call = taskService.getTasks();
call.enqueue(new Callback<List<Task>>() {
#Override
public void onResponse(Call<List<Task>> call, Response<List<Task>> response) {
if (response.isSuccessful()) {
// tasks available
} else {
// error response, no access to resource?
}
}
#Override
public void onFailure(Call<List<Task>> call, Throwable t) {
// something went completely south (like no internet connection)
Log.d("Error", t.getMessage());
}
}
I've been searching the simplest way to get Html code to String for some time now. I just need to fetch it so i can move forward with my project.
I tried:
OkHttpClient client = new OkHttpClient();
String run(String url) throws IOException {
Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.text);
String html= null;
try {
html = run("http://google.com");
} catch (IOException e) {
e.printStackTrace();
}
text.setText(html);
}
}
I got Error android.os.NetworkOnMainThreadException.
I just started developing in Android studio and I'm not an expert in Java either. I would like if someone would explain what i need to do, with examples preferably. thank you in advance
As #CommonsWare and #christian have already said, you need to make network operations in the background and for this aim Okhttp has a special method enqueue(). This will create a background thread for you and simplify your work.
In your case, change the lines inside run() method to these:
String run(String url) throws IOException {
String result = "";
Request request = new Request.Builder()
.url(url)
.build();
Response response = client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
// failure case
}
#Override
public void onResponse(Call call, Response response) throws IOException {
// success case
result = response.body().string();
}
});
}
You need to make network operations in background thread otherwise, you will get the exceptions. Android make it mandatory because network call takes a bit time and the UI-Thread will freeze.
Please refer https://github.com/square/okhttp/wiki/Recipes#asynchronous-get
and https://stackoverflow.com/a/6343299/1947419
I am an iOS Developer starting to learn Android. In Swift, creating a completion handler is very simple, but I still can't find a way to do it in Java.
I am sorry if this question is too noob for StackOverflow people.
Problem
I am creating a class to handle all my Http Request which is done using Retrofit.
I make this function is my RequestHelper.java
public static void checkEmailAvailability(String email) {
MyWebServiceAPI serviceAPI = retrofit.create(MyWebServiceAPI.class);
Call<APIResults> call = serviceAPI.checkEmailAvailability(getAuthenticationHeader(), RequestBody.create(MediaType.parse("text/plain"), email));
call.enqueue(new Callback<APIResults>() {
#Override
public void onResponse(retrofit.Response<APIResults> response, Retrofit retrofit) {
//Parse Response Json
//Get some value and place it inside an object
//ANDI WOULD LIKE RETURN SOME BOOLEAN VALUE AND SOME OTHER STRING
}
#Override
public void onFailure(Throwable t) {
//I WOULD LIKE A BOOLEAN VALUE HERE
}
});
}
I call it like this from my MainActivity
RequestHelper.checkEmailAvailability("user#user.com");
Now the function is still void but I would like for it to return something after the on the onResponse and onFailure method.
Any thoughts please?
You should pass the Callback object as a parameter to the checkEmailAvailability().
And implement the interface when you call the method from your MainActivity,and use the response parameter in the onXXX() method as the data returned to update UI.
Oh hello there, fellow SO members,
I have a web service that returns XML data using a simple get request that goes like this :
http://my-service:8082/qc/getData?paramX=0169¶mY=2
the service returns raw xml in the page according to the parameters' values.
I am trying to retrieve this data from a GET request in GWT using RequestBuilder, Request, etc.
However, the response gives me empty text, a Status code of ZERO (which doesn't mean anything and isn't supposed to happen), and so on.
Here's the simplified code that doesn't work.
public class SimpleXML implements EntryPoint {
public void onModuleLoad() {
this.doGet("http://my-service:8082/qc/getData", "0169", "2");
}
public void doGet(String serviceURL, String paramX, String paramY) {
final String getUrl = serviceURL + "?paramX=" + paramX + "&idTarification=" + paramY;
RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, getUrl);
try {
Request response = builder.sendRequest(null, new RequestCallback() {
#Override
public void onResponseReceived(Request request, Response response) {
response.getStatusCode(); // Gives me 0 (zero) :(
}
#Override
public void onError(Request request, Throwable exception) {
// ... doesn't matter for this example
}
});
} catch (RequestException e) {
// ... doesn't matter for this example
}
}
}
I don't get why this wouldn't work, since this is REALLY simple, I've seen tutorials and they all show me this way of doing things..
Thanks in advance
The reason is, that browsers do not allow cross-site requests with AJAX (see Same Origin Policy).
This means, that you can only call a service on the same server, same port (using the same protocol) as your HTML page. If you want to perform cross-site requests, you can use JSONP, as explained in http://code.google.com/webtoolkit/doc/latest/tutorial/Xsite.html.