Posting Json as Entity with scalaj-http - json

the api of scalaj-http is clean and I would like to use it for a new project, but it usually post a Json in StringEntity as parameter, like this
JSONObject TokenRequest = new JSONObject()
.put("Credentials", new JSONObject()
.put("Username", username)
.put("Password", password));
StringEntity requestBody = new StringEntity(TokenRequest.toString());
httppost.setEntity(requestBody);
Not sure if it doable with scalaj-http?

According to their github page you need to set the content-type header to application/json to send the body as json.
Http(url).postData(data).header("content-type", "application/json").asString.code

Related

Servlet doesnt write JSON Output to AJAX

Following code for my output:
PrintWriter out = response.getWriter();
ObjectMapper objectMapper = new ObjectMapper();
ToJson obj = new ToJson();
String obj1 = objectMapper.writeValueAsString(obj);
response.setContentType("application/json");
out.print(obj1);
System.out.println(obj1);
out.close();
The obj1 looks like this: {"prname1":"P1neu","anz1":"342356","prid1":"1","price1":"25"}
It should send the string out so I can parse it in my AJAX and display it but somwhow it ends up with nothing as console.log/etc doesnt display any data.
I had out.append but it also didnt work.
Use below code to send response as JSON.
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(obj1);
Please check this How to use Servlets and Ajax?
It will surely help you.

No content when using PostAsync to post JSON

Using the code below, I've managed to create a jsonArray with the following format:[{"id":3},{"id":4},{"id":5}]
var jArray = new JsonArray();
int numOfChildren = 10;
for (int i = 0; i < numOfChildren; i++)
{
if (CONDITION == true)
{
var jObj = new JsonObject();
int id = SOMEID;
jObj.SetNamedValue("id", JsonValue.CreateNumberValue(id));
jArray.Add(jObj);
}
I am now trying to send "JsonArray" to a server using PostAsync as can be seen below:
Uri posturi = new Uri("http://MYURI");
HttpContent content = new StringContent(jArray.ToString(), Encoding.UTF8, "application/json");
System.Net.Http.HttpResponseMessage response = await client.PostAsync(postUri, content);
On the server side of things though, I can see that the post request contains no content. After digging around on the interwebs, it would seem that using jArray.ToString() within StringContent is the culprit, but I'm not understanding why or if that even is the problem in the first place. So, why is my content missing? Note that I'm writing this for UWP aplication that does not use JSON.net.
After much digging, I eventually Wiresharked two different applications, one with my original jArray.ToString() and another using JSON.net's JsonConver.SerializeObject(). In Wireshark, I could see that the content of the two packets was identical, so that told me that my issue resided on the server side of things. I eventually figured out that my PHP script that handled incoming POST requests was too literal and would only accept json posts of the type 'application/json'. My UWP application sent packets of the type 'application/json; charset=utf-8'. After loosening some of my content checking on the server side a bit, all was well.
For those who are looking to serialize json without the use of JSON.net, jsonArray.ToString() or jsonArray.Stringify() both work well.
You should use a Serializer to convert it to string.
Use NewtonSoft JSON Nuget.
string str = JsonConvert.SerializeObject(jArray);
HttpContent content = new StringContent(str, Encoding.UTF8, "application/json");
System.Net.Http.HttpResponseMessage response = await client.PostAsync(postUri, content);

Submitting multipart/form with JSON with Ext-JS to JAX-RS, How to set Content-Type?

I want to submit a form that has file attachment using Ext-JS to a JAX-RS service that is using Jackson to process the JSON.
The problem that i have is that the JSON data doesn't have a Content-Type and I don't know how to set it?
Currently the request body looks something like the following:
-----------------------------4664151417711
Content-Disposition: form-data; name="productBinary"; filename="new.txt"
Content-Type: text/plain
blah
-----------------------------4664151417711
Content-Disposition: form-data; name="myData"
{"MyData": [1,2,3] }
-----------------------------4664151417711--
All good, except that the JSON section doesn't have a Content-Type and therefore I can't get the JAX-RS service to deserialise the JSON into an object
The JAX-RS service is something like:
#POST
#Path("/submit")
#Consumes("mulitipart/form-data")
public String submit( MultipartBody body )
{
MyData myData = body.getAttachmentObject("myData",MyData.class);
return "done";
}
any ideas?
UPDATE:
seems that there is no 'nice' way of doing this, instead I found that i need to call the json deserializer directly.
ObjectMapper om = new ObjectMapper();
InputStream is = body.getAttachment("myData").getDataHandler().getInputStream()
MyData md = om.readValue(is,MyData.class);

JSON response from ektorp / couchdb

For client requests to ektorp / couchdb I would like to pass JSON back to the client.
(Why not use couchdb direktly? Because I have to do some tweeks to the data on a Java layer inbetween.)
So is there for example a way to get JSON data from a CouchDbRepositorySupport queryView?
As far as I know, from consulting the documentation the following should do it
ViewResult result = db.queryView(query);
for (ViewResult.Row row : result) {
JsonNode docNode = row.getDocAsNode();
}
Here's another way:
InputStream is = db.queryForStream(query);
ObjectMapper mapper = new ObjectMapper();
JsonNode json = mapper.readTree(is);
(JsonNode and ObjectMapper are from the org.codehaus.jackson library.)

JSON, Servlet, JSP

Firstly, my HTTP POST through a URL accepts 4 parameters. (Param1, Param2, Param3, Param4).
Can I pass the parameters from the database?
Once the URL is entered, the information returned will be in text format using JSON
format.
The JSON will return either {"Status" : "Yes"} or {"Status" : "No"}
How shall I do this in servlets? doPost()
Just set the proper content type and encoding and write the JSON string to the response accordingly.
String json = "{\"status\": \"Yes\"}";
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
Instead of composing the JSON yourself, you may consider using an existing JSON library to ease the job of JSON (de)serializing in Java. For example Google Gson.
Map<String, String> result = new HashMap<String, String>();
result.put("status", "Yes");
// ... (put more if necessary)
String json = new Gson().toJson(result);
// ... (just write to response as above)
Jackson is another option for JSON object marshalling.