Upload data to server Retrofit 2 - json

i use com.github.ChiliLabs:ChiliPhotoPicker:0.3.1 to select photos to upload. It gives me such a path to the photo
file:///storage/emulated/0/KatePhotos/1641933129.jpg
my code for uploading the image to the server
fun formData(uri: ArrayList<Uri>) {
// Create Retrofit
val retrofit = Retrofit.Builder()
.baseUrl("https://httpbin.org")
.build()
// Create Service
val service = retrofit.create(APIService::class.java)
// List of all MIME Types you can upload: https://www.freeformatter.com/mime-types-list.html
// Get file from assets folder
val imgFile = File(uri[0].path)
val fields: HashMap<String?, RequestBody?> = HashMap()
fields["email"] = ("test#test.com").toRequestBody("text/plain".toMediaTypeOrNull())
val filename = imgFile.name
fields["file\"; filename=\"$filename\" "] =
(imgFile).asRequestBody("image/*".toMediaTypeOrNull())
CoroutineScope(Dispatchers.IO).launch {
// Do the POST request and get response
val response = service.uploadEmployeeData(fields)
withContext(Dispatchers.Main) {
if (response.isSuccessful) {
// Convert raw JSON to pretty JSON using GSON library
val gson = GsonBuilder().setPrettyPrinting().create()
val prettyJson = gson.toJson(
JsonParser.parseString(
response.body()
?.string() // About this thread blocking annotation : https://github.com/square/retrofit/issues/3255
)
)
println(prettyJson)
} else {
Log.e("RETROFIT_ERROR", response.code().toString())
}
}
}
}
The problem is that when I use decoding on the server, I only get a piece of the image. Tell me what I'm doing wrong and how can I fix it?
Its my response:
{
"args": {},
"data": "",
"files": {
"file": "data:image/*;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQEBAQECAgMCAgICAgQDAwIDBQQFBQUEBAQFBgcGBQUHBgQEBgkGBwgICAgIBQYJCgkICgcICAj/2wBDAQEBAQICAgQCAgQIBQQFCAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAj/wAARCAMABVYDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgE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2Tvit+z/AOHdF8RePba3jtbq7/s6ZI7HUIPsN35XmeUZbm2hhueBJ+8tJJ4sxn58FC3zL+lTGabaT2/r8tfTUlJ2Uuj/AOGA5FGfev0T8N/CL4Zr+zl4M8deI/hv4Ol0q68Ha7quteKI9fujrun6kmoXdpp5h0xLvY1s0yWMDSNaGMeY26VG5GJ8Nf2EvHmo3XwY8UfEW7s/D3w88Qapoq3wax1VJILG+lQQlbwWTWbyzB4o1SKaR43nTzVjVZWj1jD966T6O1+l25K3e/ut7bNPqZynaDn2u7dbJJt9utt99D4HoHp2r7HuP2btS+LviL43698ID4EsfDPhiS6k+waTZeIpbM28Fu8pMd7dWsiRMywygC8nhLyBgg2lBWR8Of2atM1fx98F/CfxJ+KPgjwbe+KNR0oTaChv31e3sLxlaKTfFZTWsUksbRmNXkLKZojIqLuK5UJ+05
},
"form": {
"email": "test#test.com"
},
"headers": {
"Accept-Encoding": "gzip",
"Content-Length": "387553",
"Content-Type": "multipart/form-data; boundary\u003da3942d3b-e13b-43de-9abd-642750914c37",
"Host": "httpbin.org",
"User-Agent": "okhttp/4.9.0",
"X-Amzn-Trace-Id": "Root\u003d1-61ddfc53-4b83816821e2302e6f2b8951"
},
"origin": "",
"url": "https://httpbin.org/post"
}
and so I see what php saves, even notepad considers it to be text.
In decode i see

Related

Google app scrips Slack API Get pins:list

Using Google app script as serverless for a slack bot. Having an issue returning specific values from slack API. I'm using the pins:list call. I am able to get the JSON in response and items calls but get null when trying to get the next set of values. I am looking to return "permalinks" so I can then post back into slack what items are pinned to a room. here is my script:(without giving away company details)
function GetPinns() {
const ss = SpreadsheetApp.getActiveSpreadsheet()
let url = "https://slack.com/api/pins.list?channel=C0XXXXXXXXX&pretty=1";
let payload = {
"ok": true,
"channel": "C0XXXXXXXXX"
"type": "message",
}
var options = {
"method": "get",
"payload": JSON.stringify(payload),
"headers": {
"Content-type": "application/json; charset=utf-8",
"Authorization": "Bearer xoxb-"}}
var response = UrlFetchApp.fetch(url, options)
var json = response.getContentText();
var data = JSON.parse(json);
var items = data.item.permalinks;
Logger.log(items);
}
Thank you!!
SUGGESTION
Upon reviewing Slack's official docs for pins.list method, I suppose that this sample JSON response below is the same as the actual JSON response that you're getting:
Sample JSON response:
{
"items": [
{
"channel": "C2U86NC6H",
"created": 1508881078,
"created_by": "U2U85N1RZ",
"message": {
"permalink": "https://hitchhikers.slack.com/archives/C2U86NC6H/p1508197641000151",
"pinned_to": [
"C2U86NC6H"
],
"text": "What is the meaning of life?",
"ts": "1508197641.000151",
"type": "message",
"user": "U2U85N1RZ"
},
"type": "message"
},
{
"channel": "C2U86NC6H",
"created": 1508880991,
"created_by": "U2U85N1RZ",
"message": {
"permalink": "https://hitchhikers.slack.com/archives/C2U86NC6H/p1508284197000015",
"pinned_to": [
"C2U86NC6H"
],
"text": "The meaning of life, the universe, and everything is 42.",
"ts": "1503289197.000015",
"type": "message",
"user": "U2U85N1RZ"
},
"type": "message"
}
],
"ok": true
}
You can try iterating though the items array via looping in the JSON response to get each permalinks data, as seen on this quick test below:
Quick Test
function GetPinns() {
//This sample JSON String response was from https://api.slack.com/methods/pins.list#examples
var json =
"{\"items\": [{\"channel\": \"C2U86NC6H\",\"created\": 1508881078,\"created_by\": \"U2U85N1RZ\",\"message\": {\"permalink\": \"https://hitchhikers.slack.com/archives/C2U86NC6H/p1508197641000151\",\"pinned_to\": [\"C2U86NC6H\"],\"text\": \"What is the meaning of life?\",\"ts\": \"1508197641.000151\",\"type\": \"message\",\"user\": \"U2U85N1RZ\"},\"type\": \"message\"},{\"channel\": \"C2U86NC6H\",\"created\": 1508880991,\"created_by\": \"U2U85N1RZ\",\"message\": {\"permalink\": \"https://hitchhikers.slack.com/archives/C2U86NC6H/p1508284197000015\",\"pinned_to\": [\"C2U86NC6H\"],\"text\": \"The meaning of life, the universe, and everything is 42.\",\"ts\": \"1503289197.000015\",\"type\": \"message\",\"user\": \"U2U85N1RZ\"},\"type\": \"message\"}],\"ok\": true}";
var data = JSON.parse(json);
//Iterate through the items via looping
data.items.forEach(item => {
Logger.log(item.message.permalink)
});
}
Result
Your script will look like this:
function GetPinns() {
const ss = SpreadsheetApp.getActiveSpreadsheet()
let url = "https://slack.com/api/pins.list?channel=C0XXXXXXXXX&pretty=1";
let payload = {
"ok": true,
"channel": "C0XXXXXXXXX"
"type": "message",
}
var options = {
"method": "get",
"payload": JSON.stringify(payload),
"headers": {
"Content-type": "application/json; charset=utf-8",
"Authorization": "Bearer xoxb-"
}
}
var data = JSON.parse(json);
//Iterate through the items via looping
data.items.forEach(item => {
Logger.log(item.message.permalink)
});
}
Reference
https://www.sitepoint.com/loop-through-json-response-javascript/
Thank you!!
I wound up with this in the end
var response = UrlFetchApp.fetch(url, options);
var json = JSON.parse(response.getContentText());
var items = json.items
var linkList = ""
for(var x in items) {
var link = items[x]["message"]["permalink"]
var text = items[x]["message"]["text"]
linkList += "<" + link +"|" + text +">" + "\n"
}

Post List <int> in http Flutter

I want to send a data like this :
{
"ad_title": "test",
"year": "2019",
"class": "Highline",
"files": [ 212]
}
To api in flutter. I tried to do that
var data = {
"year": selectedYear,
"class": _classController.text.toString(),
"files": json.encode(carfilesids),
};
final response = await http.post(url, body: data,headers:
{'Accept': 'application/json'});
However there's no errors in run time and when I print the value of json.encoder.convert(carfilesids) it gives me List, I got a response status code of 422 and it tells me " {"message":"The given data was invalid.","errors":{"files":["The files must be an array."]}} ". I also tried to json.encode the whole data but it goes wrong with the other data attributes.
You must use jsonEncode on your map, or else the http package will treat it as form data.
From the documentation:
If body is a Map, it's encoded as form fields using encoding. The content-type of the request will be set to "application/x-www-form-urlencoded"; this cannot be overridden.
final response = await http.post(url,
body: {
"ad_title": "test",
"year": "2019",
"class": "Highline",
"files": [ 212 ]
},
headers: {
'Accept': 'application/json'
}
);

Unexpected character (g) at position 0 when trying to parse json - HttpResponseDecorator

Whenever I try to execute below script I keep getting error, saying unexpected character (g).
Basically I want to be able to parse the json response and be able to get the upstream job name from it.
Script:
#Grapes([
#Grab(group='org.codehaus.groovy.modules.http-builder', module='http-builder', version='0.7.1'),
#Grab(group='commons-collections', module='commons-collections', version='3.2.1'),
#Grab(group='org.jsoup', module='jsoup', version='1.10.2'),
#Grab(group='org.json', module='json', version='20190722'),
#Grab(group='com.googlecode.json-simple', module='json-simple', version='1.1.1')
])
import static groovyx.net.http.ContentType.*
import groovyx.net.http.HttpResponseException
import groovyx.net.http.RESTClient
import groovy.json.JsonSlurper
import groovy.json.JsonOutput
import java.net.*
import java.util.*
import org.json.simple.*
import org.json.simple.parser.JSONParser;
def getRestClient(){
String jenkinsUrl="http://somedomainname:8080"
def restClient = new RESTClient(jenkinsUrl)
return restClient
}
def getJobsInfo(String jobname,RESTClient restClient){
def requrl= '/job/'+jobname+'/lastBuild/api/json/?pretty=true'
def response = restClient.get( path : requrl)
return response
}
def writeToPropertyFile(){
def jsonResponseObject = getJobsInfo("sampleJobName",getRestClient())
println "\n\n\n\n\n Json String :---- "+ jsonResponseObject.toString()
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(jsonResponseObject.toString());
JSONArray upstreamJobInfoArray = jsonObject.getJSONArray("causes");
for (int i = 0; i < upstreamJobInfoArray.length(); i++) {
JSONObject jobCauses = upstreamJobInfoArray.getJSONObject(i);
String upstreamProjectName = jobCauses.getString("upstreamProject");
println upstreamProjectName
}
}
writeToPropertyFile()
Error :
Json String :---- groovyx.net.http.HttpResponseDecorator#6b063470
Caught: Unexpected character (g) at position 0.
Unexpected character (g) at position 0.
at org.json.simple.parser.Yylex.yylex(Yylex.java:610)
at org.json.simple.parser.JSONParser.nextToken(JSONParser.java:269)
at org.json.simple.parser.JSONParser.parse(JSONParser.java:118)
at org.json.simple.parser.JSONParser.parse(JSONParser.java:81)
at org.json.simple.parser.JSONParser.parse(JSONParser.java:75)
at org.json.simple.parser.JSONParser$parse.call(Unknown Source)
at getUpstreamJob.writeToPropertyFile(getUpstreamJob.groovy:39)
at getUpstreamJob.run(getUpstreamJob.groovy:50)
EDIT 1 : START
JSON response that I am trying to parse :
{
"_class": "hudson.model.FreeStyleBuild",
"actions": [
{
"_class": "hudson.model.CauseAction",
"causes": [
{
"_class": "hudson.model.Cause$UpstreamCause",
"shortDescription": "Started by upstream project \"sampleJobName\" build number 712",
"upstreamBuild": 712,
"upstreamProject": "sampleJobName",
"upstreamUrl": "job/sampleJobName/"
},
{
"_class": "hudson.model.Cause$UserIdCause",
"shortDescription": "Started by user Malick, Asif",
"userId": "asifma00",
"userName": "Malick, Asif"
},
{
"_class": "com.sonyericsson.rebuild.RebuildCause",
"shortDescription": "Rebuilds build #300",
"upstreamBuild": 300,
"upstreamProject": "sampleJobName",
"upstreamUrl": "view/ABCProjectView/job/sampleJobName/"
}
]
},
{
"_class": "hudson.model.ParametersAction",
"parameters": [
{
"_class": "hudson.model.StringParameterValue",
"name": "SNAPSHOTNAME",
"value": "ABCDE_12121.2000-2121212121212"
},
{
"_class": "hudson.model.StringParameterValue",
"name": "BUILD_LABEL",
"value": "ABCDE_12121.2000"
}
]
},
{},
{},
{},
{},
{
"_class": "hudson.plugins.parameterizedtrigger.BuildInfoExporterAction"
},
{},
{},
{},
{}
],
"artifacts": [],
"building": false,
"description": null,
"displayName": "#301",
"duration": 1199238,
"estimatedDuration": 1194905,
"executor": null,
"fullDisplayName": "sampleJobName #301",
"id": "301",
"keepLog": false,
"number": 301,
"queueId": 189076,
"result": "SUCCESS",
"timestamp": 1583500786857,
"url": "http://somedomainname:8080/job/sampleJobName/301/",
"builtOn": "Server12345",
"changeSet": {
"_class": "hudson.scm.EmptyChangeLogSet",
"items": [],
"kind": null
},
"culprits": []
}
EDIT 1 : END
I have tried looking at several Stack Overflow issues, but still haven't been able to resolve it.
Please guide.
It's because you're not getting the actual JSON string, you're getting the toString() output on a groovyx.net.http.HttpResponseDecorator class.
You can see it printing it out here (it's easy to miss though... I missed it the first look 🙂):
Json String :---- groovyx.net.http.HttpResponseDecorator#6b063470
I think you need to call jsonResponseObject.data to get the parsed data, and it might even return you a Map parsed form the JSON (so you can get rid of all your JSONObject code). Test it by changing to:
def data = jsonResponseObject.data
println "\n\n\n\n\n Json ${data.getClass().name} :---- $data" jsonResponseObject.toString()
If it is a java.util.Map, you can simplify your second part from:
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = (JSONObject) jsonParser.parse(jsonResponseObject.toString());
JSONArray upstreamJobInfoArray = jsonObject.getJSONArray("causes");
for (int i = 0; i < upstreamJobInfoArray.length(); i++) {
JSONObject jobCauses = upstreamJobInfoArray.getJSONObject(i);
String upstreamProjectName = jobCauses.getString("upstreamProject");
println upstreamProjectName
}
To (using data from above):
data.actions.causes.upstreamProject.flatten().each { println it }

Use API's URL to receive json

I am accessing the api of world weather online. I have configured the url and it is displayed below-
http://api.worldweatheronline.com/premium/v1/marine.ashx?key=XXXXXXXXXXXXXXXX&q=-34.48,150.92&format=json
Note: my API key is displayed as XXXXXXXXXXXX and this is returning the following:
{
"data": {
"request": [],
"weather": [
{
"date": "2016-11-20",
"astronomy": [],
"maxtempC": "27",
"maxtempF": "80",
"mintempC": "15",
"mintempF": "58",
"hourly": [
{
"time": "0",
"tempC": "15",
...
I want to GET this json in JS and then log the value of TempC.
How can this be done?
The simplest way would be using request. You can install it with npm install request
const request = require('request')
const apiKey = 'XXXXXXXX'
let url = 'http://api.worldweatheronline.com/premium/v1/marine.ashx'
let qs = {
q: '-34.48,150.92',
format: 'json',
key: apiKey
}
request({ url, qs }, (err, response, body) => {
if (err)
return console.error(err)
if (response.statusCode != 200)
return console.error('status:', response.statusCode, body)
body = JSON.parse(body)
console.log(body.data.weather[0].hourly[0].tempC)
})

Ember incorrectly deserialize json data

So I have a Spring Boot api returning a bunch of records in a list, like that:
[
{
"uid": 16587783,
"createdAt": 1391708660000,
"name": "FRaaS",
"fullName": "caarlos0/FRaaS",
"description": "Fake RT as a Service",
"homepage": "http://fraas.herokuapp.com/",
"owner": "caarlos0",
"organization": null,
"joined": false,
"private": false
},
....
more records
]
but when I try to read it in the template, I get the following error
WARNING: Encountered "0" in payload, but no model was found for model name "0" (resolved model name using chathub-ember#serializer:-rest:.modelNameFromPayloadKey("0"))
Here is my current adapter
import DS from 'ember-data';
import Ember from 'ember';
export default DS.RESTAdapter.extend({
host: 'http://127.0.0.1:8080/v1',
primaryKey: 'uid',
headers: Ember.computed('session.data.authenticated.currentUser.backendAccessToken', function() {
return {
"Auth-Token": this.get("session.data.authenticated.currentUser.backendAccessToken"),
};
})
});
what can I do in ember to allow it to read the data as I sent? I can change the API if needed, but I would rather not to
You need to use RESTSerializer. And primaryKey is for serializer not adapter. I think you use json serializer in your app.
UPDATE
Add below to your application serializer
normalizeSingleResponse(store, primaryModelClass, payload, id, requestType) {
let typeKey = primaryModelClass.modelName;
let ret = {};
ret[typeKey] = payload;
return this._normalizeResponse(store, primaryModelClass, ret, id, requestType, true);
},
normalizeArrayResponse(store, primaryModelClass, payload, id, requestType) {
let pluralTypeKey = Ember.Inflector.inflector.pluralize(primaryModelClass.modelName);
let ret = {};
ret[pluralTypeKey] = payload;
return this._normalizeResponse(store, primaryModelClass, ret, id, requestType, false);
}