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.
Related
I am trying to download an audio .wav file from AWS using OkHTTP.
Problem
API is executing. It is giving no error, but the downloaded file size is 660B while it should be 61.92KB. When I try to download the audio from my browser using same API link, it is downloaded, however using android mobile the audio size is in bits and full audio is not downloaded.
Below is code for Downloading file
Request request = new Request.Builder()
.url(audio_url)
.build();
AwsInterceptor awsInterceptor = new AwsInterceptor(new AWSCredentialsProvider() {
#Override
public AWSCredentials getCredentials() {
return new BasicAWSCredentials(access_key_id, secret_access_key);
}
#Override
public void refresh() {
}
}, API_GATEWAY_SERVICE_NAME, region);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(awsInterceptor)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
String mMessage = e.getMessage();
Log.e("failure Response", mMessage);
call.cancel();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
byte[] rawData = response.body().bytes();
File recordingFile = new File(dir_path, file_name+".wav");
bytesToWav(recordingFile, rawData);
/*try (BufferedSource bufferedSource = response.body().source()) {
BufferedSink bufferedSink = Okio.buffer(Okio.sink(recordingFile ));
bufferedSink.writeAll(bufferedSource);
bufferedSink.close();
}*/
}
});
Solutions I tried
I tried multiple solutions like downloading using okio but didn't work.
I tried stackoverflow solution1, solution2, solution3, solution4 but nothing worked for me. I cant figure out what the problem is.
Also if there is any other way to download .wav file please let me know.
I am writing Java code where i am downloading the file from a server and i have to copy the file in my local system when the file download is complete.
I am using the below code:-
OkHttpClient.Builder builder = new OkHttpClient.Builder();
OkHttpClient client = builder.readTimeout(600, TimeUnit.SECONDS).writeTimeout(600, TimeUnit.SECONDS)
.connectTimeout(600, TimeUnit.SECONDS).build();
Request downloadRequest = new Request.Builder().url(url + fileName).addHeader("cache-control", "no-cache")
.addHeader("Authorization", token).build();
try {
Response downloadResponse = client.newCall(downloadRequest).execute();
System.out.println(downloadResponse.message());
System.out.println("got response from blob " + downloadResponse.isSuccessful() + " " + fileName);
return downloadResponse;
} catch (IOException e1) {
e1.printStackTrace();
}
return null;
}
But the request is made asynchronously and before the request is completed then response is returned which is incomplete. Can anyone please help me how can i make a request and wait till the response is completed.
Any help is highly appreciated!
Looks like you're returning the response object (not the response body content).
try something like:
return downloadedResponse.body().string()
My experience with HttpClient is such that the headers return first. The content doesn't necessarily come across the wire unless/until you consume it.
To make a synchronous GET request we need to build a Request object based on a URL and make a Call. After its execution we get back an instance of Response:
#Test
public void whenGetRequest_thenCorrect() throws IOException {
Request request = new Request.Builder()
.url(BASE_URL + "/date")
.build();
Call call = client.newCall(request);
Response response = call.execute();
assertThat(response.code(), equalTo(200));
}
You are already using synchronous method calling.
client.newCall(downloadRequest).execute();
This is a synchronous way of requesting URL. If you want to do the aysynchronous call you need to use enqueue method of Call class.
call.enqueue(new Callback() {
public void onResponse(Call call, Response response)
throws IOException {
// ...
}
public void onFailure(Call call, IOException e) {
fail();
}
});
I think problem is somewhere else. Kindly give more details why you are suspecting the current one as an asynchronous call so that we can do RCA.
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
First sorry for my English which is not my native language.
I use okhttp to do some simple asynchronous calls but my program doesn't stop immediately after the call of onResponse. It takes some seconds and then stops. I don't have this issue on Android 5 but on my desktop. I have the same issue with others URLs. Maybe there is something I did wrong. The request is performed in another thread. My network is under a proxy.
I use : okhttp-2.4.0 and okio-1.4.0 and java8.
Redirect me if this issue was already answered.
This my code : `
private final OkHttpClient client = new OkHttpClient();
public void run() throws Exception {
Settings.setProxy();
Request request = new Request.Builder()
.url("http://openlibrary.org/search.json?q=la+famille")
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
e.printStackTrace();
System.out.println("error");
}
#Override
public void onResponse(Response response) throws IOException {
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
System.out.println("coucou");
}
});
}
`
As you find out from the issue when you do an async call an ExecutorService is created and the pool is keeping the VM alive.
To shutdown the pool just get the dispatcher and close it:
client.getDispatcher().getExecutorService().shutdown();
I don't know how but this line worked for me
client.connectionPool().evictAll();
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