I wanna send data that is content-type : application/json. when I send not creating data class file but only parsing JSONObject to String, I got incorrect string like this
{\"mobile\":\"01011111111\"}" I want to send without this \. how can I remove that?
here is my code
override fun checkSMS(mobile: String): Call<NetworkResult> {
val jsonObject = JSONObject()
try {
jsonObject.put("mobile", mobile)
} catch (e: JSONException) {
e.printStackTrace()
}
showLog("jsonObject : "+jsonObject)
return service.checkSMS(jsonObject.toString())
}
#POST("smsCheck")
fun checkSMS(
#Body params: String
) :Call<NetworkResult>
Try with accumulate
val jsonObject = JSONObject()
jsonObject.accumulate("mobile",mobile)
Your POST Request #Body should be JSONObject
#POST("smsCheck")
fun checkSMS(
#Body json: JSONObject
) :Call<NetworkResult>
FYI
For nameValuePairs issue You can use JsonObject.
package com.google.gson;
JsonObject reqObject = new JsonObject();
try{
reqObject.addProperty("mobile","12345678");
}
Add this in build.gradle section
implementation "com.google.code.gson:gson:2.8.6"
Related
My server is accepting request body like this:
[
{
"key":"available",
"value":"1"
}
]
I have a interface like this:
#POST("lm/leave")
suspend fun requestLeave(
#Body body: RequestBody
): Response<LeaveResponse>
What I have tried:
val lReq: HashMap<String, String> = HashMap()
lReq.put("available", "1")
How and what should I use to generate a request like above ? Any help will be appreciated!
You can use JSONObject and JSONArray to create the request you need:
val jsonObj = JSONObject()
jsonObj.put("available", "1")
val jsonArray = JSONArray()
jsonArray.put(jsonObj)
val requestBody = RequestBody.create(null, jsonArray.toString())
requestLeave(requestBody)
JSONObject is responsible for the creating of object data representation in a json format:
{
"key":"available",
"value":"1"
}
JSONArray wraps the object into an array representation:
[
{
"key":"available",
"value":"1"
}
]
I have created JSONRequest by using volley ussing this tutorial https://www.tutorialspoint.com/how-to-use-volley-library-to-parse-json-in-android-kotlin-app
Blynk APi returns this "1"
i have this error Caused by: org.json.JSONException: Value ["1"] of type org.json.JSONArray cannot be converted to JSONObject
private fun jsonParse() {
val url = "http://blynk-cloud.com/4ae3851817194e2596cf1b7103603ef8/get/D8"
val request = JsonObjectRequest(Request.Method.GET, url, null, { response ->
try {
val JSONObject = response.getJSONArray("test")
for (i in 0 until JSONObject.length()) {
val test = JSONObject.getJSONObject(i)
val status = test.getString("test1")
textView.append("$status")
}
} catch (e: JSONException) {
e.printStackTrace()
}
}, { error -> error.printStackTrace() })
requestQueue?.add(request)
}
Obviously, the response JSON string is not correct. I checked the JSON string with the Url on Firefox, it shows:
Use this style JSON to test is nonsense, I think. If you want to test parsing JSON with Volley lib, you can use public API to test it.
This is my first time using the retrofit in android (Java) and i don't know how to do post api
in postman i use Request Body as raw JSON
{
"description": "aaaaaa",
"reportedpriority_description": "Elevé",
"reportedby": "zz",
"assetnum": "111",
"affectedperson": "ahmed"
}
someone can help me with example of code? it return empty response body
void requestcall(){
try
{
HashMap respMap = new HashMap<>();
respMap.put("Key1", "Value1");
respMap.put("Key2", "Value2");
respMap.put("Key3", "Value3");
String resultString = convertToJson(respMap);
sendToServer(resultString);
}
catch (Exception e)
{ }
}
public static String convertToJson(HashMap<String, String> respMap)
{
JSONObject respJson = new JSONObject();
JSONObject respDetsJson = new JSONObject();
Iterator mapIt = respMap.entrySet().iterator();
try
{
while (mapIt.hasNext()) {
HashMap.Entry<String, String> entry = (HashMap.Entry) mapIt.next();
respDetsJson.put(entry.getKey(), entry.getValue());
}
//change according to your response
respJson.put("RESPONSE", respDetsJson);
}
catch (JSONException e)
{
return "";
}
return respJson.toString();
}
There are two ways you can send a body for Post methods, you can either create a JSON string in the format you want. Or you can simply create a model class with the same field names as your JSON keys, and then initialize values to them while sending a request.
Model class:
class Example {
var description: String? = null
var reportedpriority_description: String? = null
var reportedby: String? = null
var assetnum: String? = null
var affectedperson: String? = null
}
Init values:
val obj = Example()
obj.description = "aaaaaa"
// and so on
You can then pass the object to your POST method.
You can refer to documentations to learn how to code the API methods.
Hope this works for you!
#Headers("Content-Type: application/json")
#POST("answer")
fun sendAnswer(#Header("token") token :String, #Body answer: SendAnswerModel):Call<SendAnswerResultModel>
here is my model class
data class Vote2019Answer(
#SerializedName("question_id") #Expose val id: Int,
#SerializedName("answer") #Expose val answer: String)
another model class
data class SendAnswerModel(
#SerializedName("answer") #Expose val answer: List<Vote2019Answer> )
You can pass json object / json array using #Body by converting the json model to POJO ( using GSON) .
Check this out !
Try the following way.
Your API endpoint
#POST("url")
Call<ResponseBody> yourAPi(#Body JSONArray jsonArray);
And API call using param data
String[] answer = {"aaa","bbb","ccc"}
JSONArray jsArray= new JSONArray();
try {
for(int i = 0; i < answer.length; i++) {
JSONObject object = new JSONObject();
object.put("question_id",i+1);
object.put("answer",answer[i]);
jsArray.put(object);
}
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// here you can call your api
Call<ResponseBody> call = yourApiService.yourAPi(jsArray);
// ........
I am trying to send an array of json objects using retrofit, while this is working with raw JSON in postman I am having trouble in Android. Right now I am just doing one value in the array, it will do more later.
Api Interface
#Headers({
"Content-Type:application/json"
})
#PUT("/People")
Call<Task> updatePeople(
#retrofit2.http.Header("Authorization") String authorization, #retrofit2.http.Body List<Person> body
);
request
fun updatePeople(person: Person, legId:Int){
val peopleList = listOf(person)
personApi.updatePeople(token, peopleList).enqueue(object : Callback<Task>{
override fun onFailure(call: Call<List<Person>>, t: Throwable)
{
//Error
}
override fun onResponse(call: Call<List<Person>>, response: Response<List<Person>>)
{
if(response.code() == 200)
{
//It works
}
}
})
}
Try to add "hasBody = true" like this:
#FormUrlEncoded
#Headers("Content-Type: application/json")
#HTTP(method = "PUT", path = "/People", hasBody = true)
Call<Task> updatePeople(#retrofit2.http.Header("Authorization") String authorization, #retrofit2.http.Body List<Person> body);