HTTPBuilder encoding utf-8 in Grails - grails

I have a problem using HTTPBuilder in Grails.
The code is something like this.
def http = new HTTPBuilder("theURL")
http.request(method, ContentType.JSON) {
uri.path = "theURI"
headers.'Authorization' = "OAuth $accessToken"
headers.'Accept' = "application/json"
headers.'content-type' = "application/json;charset=utf-8"
response.success = { resp, json ->
result = json
}
}
return result
Now the response is a JSON with "Cobro N�� 1234" but i need "Cobro Nº 1234"
I tried this with curl and the response is fine "Cobro Nº 1234", this made me think that the problem is the HTTPBuilder and not my API who response the request.
I think that it is a problem with the response encoding.

http.encoders.charset = Charsets.UTF_8

Try this:
headers.'content-type' = "application/JSON;charset=UTF-8" //capitalized
Either, try this:
#Produces(MediaType.APPLICATION_JSON + ";charset=utf-8")

Try adding this after your 'http' declaration:
http.encoderRegistry = new EncoderRegistry( charset: 'utf-8' )

I couldn't follow if the content you are sending needs to be encoded with UTF-8, or if the content you are receiving needs to be read with UTF-8.
I was having a problem sending content with UTF-8, and this is what I did.
http.request(Method.PUT) { request ->
// set headers here
request.entity = new StringEntity(json.toString(), "UTF-8")
}
I'm converting a net.sf.json.JSONObject to a String in order to pass it along as the body of the PUT call. I'm using StringEntity, and previously I wasn't setting the encoding on the StringEntity, but there is a constructor that takes an encoding. Now that I'm setting "UTF-8" there, it is working.

Related

How to POST the json payload data inside a telegram chat using the bot API?

I only get the text "1111" mentioned in the url as the output inside telegram chat and not the json data written inside the code.
import requests
from requests.structures import CaseInsensitiveDict
url = "https://api.telegram.org/bot5168xxxxx8:AAxxxxxxo/sendMessage? chat_id=#alerttest&text=1111"
headers = CaseInsensitiveDict()
headers["Content-Type"] = "application/json"
data = """
{
"stocks": "SEPOWER,ASTEC,EDUCOMP,KSERASERA,IOLCP,GUJAPOLLO,EMCO"
}
""""
resp = requests.post(url, headers=headers, data=data)
print(resp.status_code)
   
You are probably confused about the working of HTTP methods and Telegram API methods.
First step: Telegram sendMessage works with POST HTTP method.
It requires the text parameter, passed as GET parameter: otherwise you'll send an empty message.
This means, that if you're willing to include the JSON payload as text message you have to include your JSON attribute's values into the Telegram sendMessage text parameter, otherwise you won't be able to see that into the final message.
I found the following issues with the given code:
url contains a space.
chat_id value should be numeric. Use https://web.telegram.org/ to get the chat_id from the URL. It should be a negative number. If it's a channel or supergroup, you should prepend 100 after the minus sign.
&text=1111 should be removed from the URL, as text is specified in the body when using the requests.post() method.
data should be a dictionary containing key name text.
You can not specify "Content-Type": "application/json" in headers unless your data dictionary has been transcoded to json. This can be solved in the requests.post() call by either changing data= to json=, or by not specifying headers at all.
Working:
import requests
from requests.structures import CaseInsensitiveDict
url = "https://api.telegram.org/bot5168xxxxx8:AAxxxxxxo/sendMessage?chat_id=-739xxxxxx"
headers = CaseInsensitiveDict()
headers["Content-Type"] = "application/json"
data = { 'text': 'stocks: SEPOWER,ASTEC,EDUCOMP,KSERASERA,IOLCP,GUJAPOLLO,EMCO' }
resp = requests.post(url, headers=headers, json=data)
print(resp.status_code)
Working:
import requests
url = "https://api.telegram.org/bot5168xxxxx8:AAxxxxxxo/sendMessage?chat_id=-739xxxxxx"
data = { 'text': 'stocks: SEPOWER,ASTEC,EDUCOMP,KSERASERA,IOLCP,GUJAPOLLO,EMCO' }
resp = requests.post(url, data=data)
print(resp.status_code)

Groovy httpbuilder post list params

I'm trying to consume a web service from my grails project. I'm using httpbuilder 0.7.2. Below is my http client.
static def webServiceRequest(String baseUrl, String path, def data,method=Method.GET,contentType=ContentType.JSON){
def ret = null
def http = new HTTPBuilder(baseUrl)
http.request(method, contentType) {
uri.path = path
requestContentType = ContentType.URLENC
if(method==Method.GET)
uri.query = data
else
body = data
headers.'User-Agent' = 'Mozilla/5.0 Ubuntu/8.10 Firefox/3.0.4'
response.success = { resp, json ->
println "response status: ${resp.statusLine}"
ret = json
println '--------------------'
}
}
return ret
}
The issue is coming when i'm trying to send something like this:
def input = [:]
input['indexArray'] = [1,5]
api call
def response = webServiceRequest(url,uri,input,Method.POST)
when i'm printing the value of post data in my server it shows only last value of list.
{"indexArray":"5"}
it should show both 1 and 5
If you want to send json data using contenttype application/x-www-form-urlencoded you have to explicitly convert the data before adding it to the body, you can use (data as JSON).
I am using RESTClient (nice convenience wrapper on HTTPBuilder, https://github.com/jgritman/httpbuilder/wiki/RESTClient). It is as simple as this with Spock.
RESTClient restClient = new RESTClient("http://localhost:8080")
restClient.contentType = ContentType.JSON
Also it automatically parses the JSON data, so my Spock test is:
when: "we check the server health"
HttpResponseDecorator response = restClient.get([path : "/health"]) as HttpResponseDecorator
then: "it should be up"
response != null
200 == response.status
'application/json' == response.contentType

rails post parameter truncated

I have an oddity I hope someone can help with, I have an application which is uploading a reasonably long string as a post parameter, I know the web request is right because it works fine with PHP.
With Rails 4 though it seems to just chop off the string at the same point every time, yet I can't find any documentation that indicates this is normal behavior i'm assigning it like so:
mystring= params[:post_xml]
if I do the following:
mystring = request.body.read
It works fine!
Any ideas?
EDIT For clarity here's my C# request code its on port 3001 as thats the test port for rails
HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create("http://mydomain.com:3001/api/new");
ASCIIEncoding encoding = new ASCIIEncoding();
var textFromDoc = Globals.ThisAddIn.Application.ActiveDocument.Content.Text;
// string postData = "content=" + textFromDoc;
//byte[] data = encoding.GetBytes(postData);
byte[] data = Encoding.UTF8.GetBytes(textFromDoc);
httpWReq.Method = "POST";
httpWReq.ContentType = "text/xml; encoding='utf-8'";
//"application/x-www-form-urlencoded";
httpWReq.ContentLength = data.Length;
using (Stream stream = httpWReq.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse();
string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
System.Windows.Forms.MessageBox.Show(responseString);
}
catch (System.Exception excep)
{
System.Windows.Forms.MessageBox.Show(excep.Message);
}
ActionController::StrongParameters#params is very different from ActionDispatch::Request#body. These two methods serve different purposes.
Check out Chapter 4: Parameters in the Action Controller Overview to learn more.

Highcharts-Export Server for Java JSON parsing issue

I configured the highchart export server for Java from the current master in GitHub. When I tried to export an image using the demo page a corrupted file was returned. I have debugged to code and found out the following message is returned as the result in validate method in ServerObjectFactory.java
String result = server.request("{\"status\":\"isok\"}");
The value of the result String is "Failed rendering:SyntaxError: Unable to parse JSON string"
What can be the cause for this issue.
Thank You
That's very strange. The syntax of the JSON string is syntactically correct. I can point out where from the error is generated.
In the highcharts-convert.js file in highcharts-ecport-convert/src/main/resources/phantomjs the incoming request is expected to be a JSON string and is parsed, see Line 469
function (request, response) {
var jsonStr = request.post,
params,
msg;
try {
params = JSON.parse(jsonStr); // L469
if (params.status) {
// for server health validation
response.statusCode = 200;
response.write('OK');
response.close();
} else {
....
Set in a console.log(jsonStr) before JSON.parse(jsonStr) . I hope this give you a clue of why it's throwing a error.

Delete entry from database with WinJS and OData

I'm trying to delete an entry from the database by odata. I get the error message
{"error":{"code":"","message":{"lang":"en-US","value":"Bad Request - Error in query syntax."}}}
my code:
function deleteMonthEntry() {
var item = actMonthEntries.getItem(listIndex);
var queryString = "Stundens(" + item.data.datensatz_id + ")?$format=json";
var requestUrl = serviceUrl + queryString;
WinJS.xhr({
type: "delete",
url: requestUrl,
headers: {
"Content-type": "application/json"
}
}).done(
function complete(response) {
},
function (error) {
console.log(error);
}
);
}
My request URL looks like this:
requestUrl = "http://localhost:51893/TimeSheetWebservice.svc/Stundens(305233)?$format=json"
Thanks
Marlowe
At least I found the solution:
I've entered an filter request to my service like this:
TimeSheetWebservice.svc/Stundens?$filter=datensatz_id eq 305221
this returned the correct entry with this link:
TimeSheetWebservice.svc/Stundens(305221M)
So if I enter a M after the ID, everything works fin. But I have no idea where this M comes from.
Can anyone tell me the reason for this M? It does not belong to the ID. The ID is this
305221
Marlowe
Are you sure the server you're talking to supports the $format query option? Many don't. I would try removing that part of the request URI, and instead modify your headers value to specify an Accept header:
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
}
For servers where $format is allowed, giving it a json value is equivalent to providing an Accept header with the application/json MIME type.
In general, for a DELETE operation, the Accept header or $format value only matters for error cases. With a successful DELETE, the response payload body will be empty, so there's no need for the server to know about your format preference.

Resources