Trying to implement RapidApi on Android Studio - java

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

Related

OkHTTP downloaded file is empty

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.

retrofit2 get responseBody in onFailure()

When I fail to parse the json from the server, I try to collect the situation.
I can see what the server gave me using the class that implements the Interceptor.(LoggingInterceptor)
However, I do not seem to be able to get the value in 'onFailure()', a situation where I need to collect errors. Because it only provides 'Call' and 'Throwable'. How do I get raw data from the server in 'onFailure()'?
Below is my code.
LoggingInterceptor
public class LoggingInterceptor implements Interceptor {
//로그에 쓰일 tag
private static final String TAG = CalyApplication.class.getSimpleName() + "/" + LoggingInterceptor.class.getSimpleName();
#Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
long t1 = System.nanoTime();
Response response = chain.proceed(request);
long t2 = System.nanoTime();
String responseString = new String(response.body().bytes());
//yes, I can see response in here. but I need it in 'onFailure()'.
Logger.i(TAG, "code : " + response.code() + "\n" + responseString);
return response.newBuilder()
.body(ResponseBody.create(response.body().contentType(), responseString))
.build();
}
}
Actrivity
void fetchData(){
ApiClient.getService().test(
"test"
).enqueue(new Callback<BasicResponse>() {
#Override
public void onResponse(Call<BasicResponse> call, Response<BasicResponse> response) {
BasicResponse body = response.body();
switch (response.code()){
case 200:
break;
default:
break;
}
}
#Override
public void onFailure(Call<BasicResponse> call, Throwable t) {
//I want get Response object in here!
//but it only provides Call&Throwable
}
});
}
Thanks!
If you get a 4xx or 5xx (error)status code then the onResponse is called, not the onFailure. You get a response body(2xx) or error body accordingly only if the call was successful. So in onResponse you should have the following structure:
if (response.isSuccessful()) {
// Get response body
} else if (response.errorBody() != null) {
// Get response errorBody
String errorBody = response.errorBody().string();
}
Edit: More info about how to retrieve the errorBody can be found here.

AWS API Gateway endpoint works fine in postman, returns 400 Bad Request in Android App

So I am getting familiar with AWS Lambda + API Gateway and am reaching a strange error. The endpoint works fine in Postman, but when I try and implement it in my app, I get a status error for 400. Here is my code:
final String body = "Name";
final byte[] content = body.getBytes(StringUtils.UTF8);
final ApiRequest apiRequest = new ApiRequest(client.getClass().getSimpleName())
.withPath("/path")
.withHttpMethod(HttpMethodName.valueOf("POST"))
.addHeader("Content-Type", "application/json")
.addHeader("Content-Length", String.valueOf(content.length))
.withBody(content);
new Thread(new Runnable() {
#Override
public void run() {
try {
Log.e("TRY", "Thread trying");
// Invoke the API
final ApiResponse response = client.execute(apiRequest);
final int statusCode = response.getStatusCode();
final String statusText = response.getStatusText();
Log.e("API_RESPONSE", "Response Status: " + statusCode + " " + statusText);
// TODO: Add your custom handling for server response status codes (e.g., 403 Forbidden)
} catch (final AmazonClientException exception) {
// Log.e(LOG_TAG, exception.getMessage(), exception);
// TODO: Put your exception handling code here (e.g., network error)
}
}
}).start();

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

I got userinfo, how get user posts from wall?

I started work with Vkontakte android SDK, and doing it well). I made authorization, and got userFirstName, userLastName and userPhoto. But I have no idea how get user wall, or user posts from user wall. It should be similar, and I see response #2 in logcat, but I don't really know how parse it???
//Prepare request for userName and photo
final VKRequest request1 = VKApi.users().get(VKParameters.from(VKApiConst.FIELDS, "photo_100, contacts"));
//Prepare request for userWall
final VKRequest request2 = VKApi.wall().get(VKParameters.from(VKApiConst.OWNER_ID));
//Parallel executing requests
VKBatchRequest batch = new VKBatchRequest(request1, request2);
batch.executeWithListener(new VKBatchRequest.VKBatchRequestListener() {
#Override
public void onComplete(VKResponse[] responses) {
super.onComplete(responses);
//Work with responses
//*****
//UserName and photo response
//*****
VKApiUserFull user = ((VKList<VKApiUserFull>) responses[0].parsedModel).get(0);
Ion.with(ivUserPhoto).placeholder(R.drawable.ic_launcher)
.error(R.drawable.ic_launcher)
.load(user.photo_100);
tvUserName.setText(user.first_name + " " + user.last_name);
//********
//Wall response similar sa userResponse...
//********
VKApiPost mPost = ((VKList<VKApiPost>) responses[1].parsedModel).get(0);
Log.e("post name", mPost.toString());
}
#Override
public void onError(VKError error) {
//Error;
}
});
Here right code, tnx Dreddik <-- vk android sdk developer.
VKRequest request2 = VKApi.wall().get(VKParameters.from(VKApiConst.OWNER_ID, VKSdk.getAccessToken().userId, VKApiConst.EXTENDED, 1));
request2.executeWithListener(new VKRequestListener() {
#Override
public void onError(VKError error) {
}
#Override
public void onComplete(VKResponse response) {
VKList<VKApiPost> posts = (VKList<VKApiPost>) response.parsedModel;
VKApiPost post = posts.get(0);
Log.d("Post:", post.toString());
}
});

Categories

Resources