POST Request on kotlin - android

I am trying to execute a link so that I can control an ESP32 using Kotlin in Android Studio, but it is unable to execute it the same way a WebView can (I use the WebView to get a video feed, and it is able to transfer the video). The below is my code
Activity
val url = URL(ipcomm2)
val con: HttpURLConnection = url.openConnection() as HttpURLConnection
con.requestMethod = "POST"
WebView
setContentView(webview)
webview.loadUrl(IPfeed)
Can someone explain why this is the case? Thanks.

You need to call getInputStream and read it out.
See https://developer.android.com/reference/java/net/HttpURLConnection

Related

How to get HTML input in kotlin?

I want to read a html site in a string with kotlin.
But I cannot find how I even get the information from the website or which command I need for it.
The following code reads the content of http://www.android.com/ and outputs the text in the log.
val url = URL("http://www.android.com/")
val urlConnection = url.openConnection() as HttpURLConnection
try {
val text = urlConnection.inputStream.bufferedReader().readText()
Log.d("UrlTest", text)
} finally {
urlConnection.disconnect()
}
See https://developer.android.com/reference/java/net/HttpURLConnection on how interact with HTTP servers in Android.
Kotlin provides the extension methods bufferedReader() and readText which make reading streams more convenient.
You can make use of Jsoup library
Jsoup html parser

Why Instagram GET request return "405 Method not allowed"?

I can easily GET data through the following request:
https://api.instagram.com/v1/tags/nofilter/media/recent?access_token=my_access_token
using my web browser. And all data is correct.
But when I trying to request using Android
URL url = new URL(urlStr);
cn = (HttpsURLConnection) url.openConnection();
cn.setDoInput(true);
cn.setDoOutput(true);
cn.setRequestProperty("access_token", my_access_token );
cn.setRequestMethod("GET");
cn.connect();
I getting "405 Method not allowed" response. Why? How to access Instagram API through the Android.
Also I want to note that access token is getting well in same manner but with method POST and some output message (as described in manual), so I am sure that my_access_token is correct and up to date.
Best Regards
Ekaterina

How to load URL in android Web View if HTTP or HTTPS not include in given URL

I have an project where I want to load some url came from webservice into a webView but. for that I am facing the following problem. Please help.
url = "www.facebook.com"
wv.loadUrl(url);
for above code I got an error say unable load webpage.
But if i changed this to
url = "https://www.facebook.com"
its working but I need to load url without having http or https mentioned .
Please help me on this.
add this by your own code like
String urlCameFromServer = "www.facebook.com";
if(!urlCameFromServer.contains("http")) {
urlCameFromServer = "http://"+urlCameFromServer;
}
wv.loadUrl(urlCameFromServer);

Android HttpURLConnection content length

I am trying to download files from a server in android and show progress dialog using code very similar to the answer provided in this thread but i am not able to get content length in HttpURLConnection's getContentLength() method. Content length for all files is -1.
For the same file, i get correct content length in iOS app with NSHTTPURLResponse's expectedContentLength method.
Is there some basic difference in the way these methods fetch the content length for an http connection/response?
EDIT 1:
Tried following few things as suggested some answers and comments.
Set Accept-Encoding header to identity
Fetching the content length as string (from header field Content-Length) and then converting it to long
Tried conn.getContent().toString().length() instead of getContentLength()
None of these worked for me yet.
What baffles me most is i get the content length in iOS but not on android.
EDIT 2:
Heres my iOS and Android code for comparison -
iOS:
NSURLRequest *request = [NSURLRequest requestWithURL:self.url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:1200.0];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
[connection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[connection start];
Android:
URL url = new URL(downloadUrlString);
connection = (HttpURLConnection) url.openConnection();
connection .setRequestProperty("Accept-Encoding", "identity");
connection.connect();
The only difference i can see is caching.
So i added following line in android code as well but nothing changed.
connection.setUseCaches(true);
try this:
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn .setRequestProperty("Accept-Encoding", "identity");
conn.connect();
if you just need to content length, can you try
conn.getContent().toString().length()
where conn is the HttpURLConnection object
Root cause for this problem turned out to be Cookies.
I am using a web view in one of the activities in my application. Some cookies are stored by the web view. All other REST api and file download requests work without those cookies however for a particular type of requests, the cookies are necessary.
Apparently, android web view and the connection requests do not share cookies out of the box like iOS. As a result i had to make changes in my code to make sure that the HttpUrlConnection uses WebKit's cookie store. I did it using method described in the accepted answer for this question.

Searching for code to log raw HTTP+cookies from Android HttpURLConnection

Has anyone released code to show the full HTTP request/response headers, any intermediate redirects, and any cookie data for the Android HttpURLConnection? This would be similar to Firefox Web Console
I roughly know how to write this myself, but 1) it's a non-trivial amount of code 2) it's tricky to get this kind of code to work in all instances. So i'm interested in finding a readymade solution. I know how to tcpdump the emulator, but I'm searching for code to print this information into the Android Log class for really quick runtime debugging.
for header fields
URL url = new URL(str_url);
HttpURLConnection conection = (HttpURLConnection) url.openConnection();
conection.setConnectTimeout(TIMEOUT_SOCKET);
conection.setReadTimeout(TIMEOUT_CONNECTION);
conection.addRequestProperty("Accept-Encoding", "gzip");
RedirectLocations locations = new RedirectLocations();
// here u get all header fields and properties write it in logs
conection.getHeaderFields();
conection.getRequestProperties();
// conection.getOutputStream().write(buffer);
// download the file
InputStream is = conection.getInputStream();
// This is file path were a; quiz data will get saved.
// String file_path = context.getDir(folder,Activity.MODE_PRIVATE).getAbsolutePath();
return unzip(is,save_file_path);
for redirects
link
after u get response, again u ve to look for header fields

Categories

Resources