How to get html source to String using OkHttp - Android - java

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

Related

OkHttpClient authenticator without retrofit

Im trying to refresh an Access token in my application following this solution.
My actual problem is handling the callback and then return the new request in the authenticate method.
I tried using an interface to return a String from my callback method but then I cant assign it to a variable, nor can I return the new request from there since its inside my onResponseListener.
How can I solve this issue?
public Request authenticate(Route route, Response response) throws IOException {
// GetAuthRequest is a void method, and I cant assign a String value on the callback.
getAuthRequest(new AuthResponse() {
#Override
public Request onSuccess(String token) {
return response.request().newBuilder()
.header("Authorization", "Bearer " + token)
.build();
}
});
I was using an Asynchronous call instead of Synchronous. Ended up making a method that returns an String like so:
private String getAuthRequest() {
// Make the request above
try (Response response = httpClient.newCall(request).execute()) {
JSONObject jsonObject = new JSONObject(response.body().string());
return jsonObject.getString("access_token");
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return null;
}

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 wait for the HTTP request to get completed in java

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.

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