Tuesday 16 July 2019

android - how to POST a url Kotlin





Get a url like "http://TEST/Data.php?Name=ABC&Number=12"



Want to post this url ,but not open this link.




Then Name and Number columns will change into ABC & 12.



setOnClickListener:



btn_send.setOnClickListener{

val i = Intent(Intent.ACTION_VIEW, Uri.parse("http://TEST/Data.php?Name=ABC&Number=12"))
startActivity(i)

}


This will open the link in a browser. How can I just post this url but not open it?



with this code my app crushed after click button:





btn_send.setOnClickListener{
URL(url).readText()
}


9/18 update----------------------------------



tring OKHTTP but nothing happened





fun get() {
val client = OkHttpClient()
val url = URL("http://TEST/Data.php?Name=ABC&Number=12")

val request = Request.Builder()
.url(url)
.build()
OkHttpClient().newCall(request)


root.btn_submit.setOnClickListener {
get()
}


if I change OkHttpClient().newCall(request) into OkHttpClient().newCall(request).execute() app will crush



I think is there a problem when i send request to HTTP which is unsafe cause the error


Answer



You just cannot directly open a POST URL in browser.




You have to use Library like one of the following:




  • Retrofit

  • Volley

  • OkHttp



Or you can open it in WebView like below




WebView webview = new WebView(this);
setContentView(webview);
byte[] post = EncodingUtils.getBytes("Name=ABC&Number=12", "BASE64");
webview.postUrl("http://TEST/Data.php", post);


convert the above code into Kotlin


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...