OkHTTP downloaded file is empty - java

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.

Related

Sending data from android to esp8266

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.

Trying to implement RapidApi on Android Studio

I am trying to implement twinword word dictionary API on Android Studio.
The error message I got is:
I/OkHttpClient: Callback failure for call to https://twinword-twinword-bundle-v1.p.rapidapi.com/...
java.io.IOException: Unexpected code Response{protocol=http/1.1, code=403, message=Forbidden, url=https://twinword-twinword-bundle-v1.p.rapidapi.com/word_example/?entry=mask}
at com.example.anew.SentenceFramer$1.onResponse(SentenceFramer.java:58)
at com.squareup.okhttp.Call$AsyncCall.execute(Call.java:177)
at com.squareup.okhttp.internal.NamedRunnable.run(NamedRunnable.java:33)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:760)
I believe the message is forbidden because it cannot access the rapidAPI and I think the problem is I couldn't figure out what is the Project Key as I couldn't find it anywhere in RapidAPI website. Or does the problem actually lies in my codes?
RapidApiConnect connect = new RapidApiConnect("I put my project name here", "I dont know where to find project key");
String object_1;
String host = "twinword-twinword-bundle-v1.p.rapidapi.com";
String API_KEY = "this is the api key";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sentence_framer);
object_1 = getIntent().getStringExtra("First Object");
Log.d("EDMTERROR", object_1);
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://twinword-twinword-bundle-v1.p.rapidapi.com/word_example/?entry=mask")
.get()
.addHeader("x-rapidapi-host", host)
.addHeader("x-rapidapi-key", API_KEY)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
Log.d("EDMTERROR", "onfailure");
e.printStackTrace();
}
#Override
public void onResponse(Response response) throws IOException {
Log.d("EDMTERROR", "masalah");
try (ResponseBody responseBody = response.body()) {
if (!response.isSuccessful()) {
Log.d("EDMTERROR", "unexpected code");
throw new IOException("Unexpected code " + response);
}
Headers responseHeaders = response.headers();
Log.d("EDMTERROR", "headers");
for (int i = 0, size = responseHeaders.size(); i < size; i++) {
System.out.println(responseHeaders.name(i) + ": " + responseHeaders.value(i));
}
System.out.println(responseBody.string());
}
This is my first time doing this, so I haven't got the slightest clue on how to fix this. The website Im trying to reach is https://rapidapi.com/twinword/api/word-dictionary?endpoint=53aa5089e4b0a798dbd1a61d.
Please help, I need this for my final year project...
It's looks like you haven't subscribed to the API on rapidapi.com (https://rapidapi.com/twinword/api/word-dictionary/pricing)
also, I couldn't find the endpoint you are trying to use (/word_example), looks like the right endpoint is /example.
You can always contact them at support#rapidapi.com

How to get html source to String using OkHttp - Android

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

How to add headers to ZeroCopyPost

I am trying to upload an image file to a web storage server using zero copy post.
The implementation comes from the example in the Apache website. I've changed some parts from the example so that the response is not downloaded in a file.
Here's the source code that I have changed.
private void upload() throws Exception {
CloseableHttpAsyncClient httpclient = HttpAsyncClients.createDefault();
try {
httpclient.start();
File upload = new File("C:\\Users\\Jee\\profile.png");
ZeroCopyPost httpost = new ZeroCopyPost(requestURL+upload.getName(), upload,
ContentType.create("image/png"));
HttpAsyncResponseConsumer consumer = new BasicAsyncResponseConsumer();
Future<File> future = httpclient.execute(httpost, consumer, null);
File result = future.get();
System.out.println("Response file length: " + result.length());
System.out.println("Shutting down");
} finally {
httpclient.close();
}
System.out.println("Done");
}
I need to add headers to this POST request. How is it done?
ZeroCopyPost zeroCopyPost = new ZeroCopyPost(
URI.create("/"),
new File("stuff"),
ContentType.DEFAULT_BINARY) {
#Override
protected HttpEntityEnclosingRequest createRequest(
final URI requestURI, final HttpEntity entity) {
HttpEntityEnclosingRequest request = super.createRequest(requestURI, entity);
request.setHeader("my-header", "whatever");
return request;
}
};
Overriding ZeroCopyPost#createRequest is the recommended way. Overriding #generateRequest per #Robert Rowntree recommendation would work as well.

asyncHttpClient no onSuccess or onFailure run

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

Categories

Resources