I want to send data to my url using Kotlin. How can I do it? I use Retrofit with field post but didn't work. Http request may be work but I couldn't find a way fits. Should sending datas be json or not?
MainActivity
lifecycleScope.launch {
doPostRequest()
}
private suspend fun doPostRequest() {
withContext(Dispatchers.IO) {
//
}
}
My Php file
<?php
$tuccar_id = $_POST['merchant_id'];
$tuccar_key = $_POST['merchant_key'];
$tuccar_salt = $_POST['merchant_salt'];
$tuccar_oid = $_POST['merchant_oid'];
$sepet = $_POST['user_basket'];
$mail = $_POST['email'];
$odeme_tutari = $_POST['payment_amount'];
$sepet = $_POST['user_basket'];
$kartsahibi = $_POST['cc_owner'];
$kartno = $_POST['card_number'];
$kartay = $_POST['expiry_month'];
$kartyil = $_POST['expiry_year'];
$kartcvv = $_POST['cvv'];
$usern = $_POST['user_name'];
$useradd = $_POST['user_address'];
$usertel = $_POST['user_phone'];
$user_basket = htmlentities(json_encode(array(
array($sepet, $odeme_tutari, 1)
)));
print_r($_POST);
$result = 1;
return $result;
?>
Related
I am trying to call get api using an AWS signing method but not able to get the response.
Below is my code.
val secretkey = "E+t5/nDf6/NKNJBjbsdjv"
val accesskey = "DJKSBDKSBNKFGNBFG"
val credentials: AWSCredentials = BasicAWSCredentials(accesskey, secretkey)
val API_GATEWAY_SERVICE_NAME = "s3"
val requestAws: Request<*> = DefaultRequest<Any?>(API_GATEWAY_SERVICE_NAME)
val uri = URI.create("https://s3.us-west-2.amazonaws.com/..../../sample")
requestAws.endpoint = uri
requestAws.resourcePath = "https://s3.us-west-2.amazonaws.com/..../../sample"
requestAws.httpMethod = HttpMethodName.GET
val signer = AWS4Signer() signer . setServiceName (API_GATEWAY_SERVICE_NAME)
signer.setRegionName("us-west-2")
signer.sign(requestAws, credentials)
val headers = requestAws.headers
val key: MutableList<String> = ArrayList()
val value: MutableList<String> = ArrayList()
for ((key1, value1) in headers)
{
key.add(key1) value . add (value1)
}
val httpClient = OkHttpClient()
val request: okhttp3.Request = okhttp3.Request.Builder()
.url("https://s3.us-west-2.amazonaws.com/..../../sample")
.addHeader(key[0], value[0])
.addHeader(key[1], value[1])
.addHeader(key[2], value[2])
.addHeader("X-Amz-Content-Sha256",
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")
.build()
val response: okhttp3.Response = httpClient.newCall(request).execute()
Log.i("LOG", response.body.toString())
Not able to figure out, what I am doing mistake.
Please help me out with this issue.
If you want to create an Android app written in Kotlin and invokes AWS Services, use the AWS SDK for Kotlin.
This SDK has strongly typed Service Clients that you can use in an Android Studio project that lets you invoke a given service. (as opposed to using okhttp3.Request, etc)
For example, here is Kotlin code that invoke SNS using a Strongly typed service client named SnsClient.
// Get all subscriptions.
fun getSubs(view: View) = runBlocking {
val subList = mutableListOf<String>()
val snsClient: SnsClient = getClient()
try {
val request = ListSubscriptionsByTopicRequest {
topicArn = topicArnVal
}
val response = snsClient.listSubscriptionsByTopic(request)
response.subscriptions?.forEach { sub ->
subList.add(sub.endpoint.toString())
}
val listString = java.lang.String.join(", ", subList)
showToast(listString)
} catch (e: SnsException) {
println(e.message)
snsClient.close()
}
}
fun getClient() : SnsClient{
val staticCredentials = StaticCredentialsProvider {
accessKeyId = "<Enter key>"
secretAccessKey = "<Enter key>"
}
val snsClient = SnsClient{
region = "us-west-2"
credentialsProvider = staticCredentials
}
return snsClient
}
TO learn how to use the AWS SDK for Kotlin, see
AWS SDK for Kotlin Developer Guide
I'm building an android app just to show or convert some cripto to USD.. But I dont know how to use and API and get the exact price value of bitcoin(any cripto)...How do I filter the json to get just the right value?
private fun converter(){
val selectedCurrency = findViewById<RadioGroup>(R.id.radioGroup)
val editField = findViewById<EditText>(R.id.edit_field)
val value = editField.text.toString()
if (value.isEmpty() || value == ".")
return
Thread{
//Para here
val url = URL("https://api.coinmarketcap.com/data-api/v3/cryptocurrency/listing?start=1&limit=500")
val conn = url.openConnection() as HttpsURLConnection
try {
val data = conn.inputStream.bufferedReader().readText()
// {"price": 32000.000} what i want to get and idk how
val obj = JSONObject(data)
runOnUiThread{
val res = obj
result.text = res.toString()
result.visibility = View.VISIBLE
}
}finally{
conn.disconnect()
}
}.start()
I'm trying to build a network module for Multiplatform project with ktor.
My code for GET request is something like this:
val result = httpClient.get<HttpResponse> {
url {
protocol = baseProtocol
host = baseUrl
encodedPath = urlPath
}
}
In some point my path contain a user id like this /users/{user_id}.
I can do a search and replace in string and replace this user_id with actual value, BUT is there any other way to do this? any ktor specific way.
For example with Retrofit we have this:
#GET("users/{user_id}/")
SomeData getUserData(#Path("user_id") String userId);
EDIT: adding more code
val result = httpClient.get<HttpResponse> {
url {
protocol = baseProtocol
host = baseUrl
var requestPath = request.requestPath.value
request.path?.forEach {
requestPath = requestPath.replace(it.first, it.second)
}
encodedPath = requestPath
if (request.parameters != null) {
parameters.appendAll(getParametersFromList(request.parameters))
}
}
the request.path?.forEach { requestPath = requestPath.replace(it.first, it.second)} replacing any runtime path value.
I'm using Xamarin Forms to consume REST Api from NetFlix but i get this issue in Popup:
System.Net.WebException: Error: NameResolutionFailure
Why o get this error?
My Code:
private HttpClient client = new HttpClient();
private List<Movie> movies;
public async Task<List<Movie>> LocalizaFilmesPorAtor(string ator)
{
if (string.IsNullOrWhiteSpace(ator))
{
return null;
}
else
{
string url = string.Format("http://netflixroulette.net/api/api.php?actor={0}", ator);
var response = await client.GetAsync(url);
if (response.StatusCode == HttpStatusCode.NotFound)
{
movies = new List<Movie>();
} else
{
var content = await response.Content.ReadAsStringAsync();
var _movies = JsonConvert.DeserializeObject<List<Movie>>(content);
movies = new List<Movie>(_movies);
}
return movies;
}
}
In debug mode said the error is in this code
string url = string.Format("http://netflixroulette.net/api/api.php?actor={0}", ator);
var response = await client.GetAsync(url);
He stops in there, the url recive the url + actor name but in next line the response stay null.
PS: I give Internet permission to my App in Manifest!
nuget packages: Microsoft HTTP Client Libraries and Newtonsoft.Json.
try this:
private HttpClient client = new HttpClient();
private List<Movie> movies;
public async Task<List<Movie>> LocalizaFilmesPorAtor(string ator)
{
if (string.IsNullOrWhiteSpace(ator))
{
return null;
}
else
{
var client = new HttpClient();
client.BaseAddress = new Uri("http://netflixroulette.net/");
HttpResponseMessage response = client.GetAsync("api/api.php?actor={0}", ator);
if(response.IsSuccessStatusCode)
{
var json = response.Content.ReadAsStringAsync().Result;
var _movies = JsonConvert.DeserializeObject<List<Movie>>(json);
movies = new List<Movie>(_movies);
}
else
{
movies = new List<Movie>();
}
return movies;
}
}
PS: if movies = new List(_movies) not work, try foreach.
Why cant you try Refit?
Refit is a library heavily inspired by Square's Retrofit library, and it turns your REST API into a live interface
What you just need to do is:
Add Refit from Nuget Package
Create an Interface with any name
Import the Refit (Using Refit)
here is a sample code for the interface
public interface ISampleName
{
[Get("api/api.php?actor={ator}")]
async Task<List<Movie>> LocalizaFilmesPorAtor(string ator);
}
After that, then you can call it this way:
var SampleNameApi = RestService.For<ISampleName>("http://netflixroulette.net/");
var response= await SampleNameApi.LocalizaFilmesPorAtor("Sample");
I believe this will help you.
For More Information https://github.com/paulcbetts/refit
I had this issue too because my URL was malformed. Double check if your URL is correct with Postman/Browser.
I have integrated Firebase Authentication and Storage using this guide and it was working just fine. Yesterday suddenly, I am unable to get to refresh the token. Every time I call the refreshToken(idToken) method, I get a 400:Invalid Id Token error.
I didn't change the code. I was testing the app one day and it was working fine, I checked that same app the next day and it wasn't working. I have no idea what to do. Any help is greatly appreciated.
Here is the code I am using to refresh the token:
private function refreshToken(idToken:String):void
{
trace("refreshing id token");
var header:URLRequestHeader = new URLRequestHeader("Content-Type", "application/json");
var myObject:Object = new Object();
myObject.grant_type = "authorization_code";
myObject.code = idToken;
var request:URLRequest = new URLRequest("https://securetoken.googleapis.com/v1/token?key="+FIREBASE_API_KEY);
request.method = URLRequestMethod.POST;
request.data = JSON.stringify(myObject);
request.requestHeaders.push(header);
var loader:URLLoader = new URLLoader();
loader.addEventListener(flash.events.Event.COMPLETE, refreshTokenLoaded);
loader.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
loader.load(request);
}
Firebase recently changed the way you get an access_token.
I have updated the guide to reflect the changes, you now need to add an extra parameter when logging in.
private function login(email:String, password:String):void
{
var myObject:Object = new Object();
myObject.email = email;
myObject.password = password;
myObject.returnSecureToken = true; <-- New parameter
var header:URLRequestHeader = new URLRequestHeader("Content-Type", "application/json");
var request:URLRequest = new URLRequest("https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyPassword?key="+FIREBASE_API_KEY);
request.method = URLRequestMethod.POST;
request.data = JSON.stringify(myObject);
request.requestHeaders.push(header);
var loader:URLLoader = new URLLoader();
loader.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
loader.addEventListener(flash.events.Event.COMPLETE, signInComplete);
loader.load(request);
}
In the response you will now get a refreshToken, you must exchange it for an access token with the following function:
private function refreshToken(refreshToken:String):void
{
var header:URLRequestHeader = new URLRequestHeader("Content-Type", "application/json");
var myObject:Object = new Object();
myObject.grant_type = "refresh_token";
myObject.refresh_token = refreshToken;
var request:URLRequest = new URLRequest("https://securetoken.googleapis.com/v1/token?key="+FIREBASE_API_KEY);
request.method = URLRequestMethod.POST;
request.data = JSON.stringify(myObject);
request.requestHeaders.push(header);
var loader:URLLoader = new URLLoader();
loader.addEventListener(flash.events.Event.COMPLETE, refreshTokenLoaded);
loader.addEventListener(IOErrorEvent.IO_ERROR, errorHandler);
loader.load(request);
}