Set headers in a groovy post request - post

I need to set a header in a post request: ["Authorization": request.token]
I have tried with wslite and with groovyx.net.http.HTTPBuilder but I always get a 401-Not authorized which means that I do cannot set the header right.
I have also thought of logging my request to debug it but I am not able to do that either.
With wslite this is what I do
Map<String, String> headers = new HashMap<String, String>(["Authorization": request.token])
TreeMap responseMap
def body = [amount: request.amount]
log.info(body)
try {
Response response = getRestClient().post(path: url, headers: headers) {
json body
}
responseMap = parseResponse(response)
} catch (RESTClientException e) {
log.error("Exception !: ${e.message}")
}
Regarding the groovyx.net.http.HTTPBuilder, I am reading this example https://github.com/jgritman/httpbuilder/wiki/POST-Examples but I do not see any header setting...
Can you please give me some advice on that?

I'm surprised that specifying the headers map in the post() method itself isn't working. However, here is how I've done this kind of thing in the past.
def username = ...
def password = ...
def questionId = ...
def responseText = ...
def client = new RestClient('https://myhost:1234/api/')
client.headers['Authorization'] = "Basic ${"$username:$password".bytes.encodeBase64()}"
def response = client.post(
path: "/question/$questionId/response/",
body: [text: responseText],
contentType: MediaType.APPLICATION_JSON_VALUE
)
...
Hope this helps.

Here is the method that uses Apache HTTPBuilder and that worked for me:
String encodedTokenString = "Basic " + base64EncodedCredentials
// build HTTP POST
def post = new HttpPost(bcTokenUrlString)
post.addHeader("Content-Type", "application/x-www-form-urlencoded")
post.addHeader("Authorization", encodedTokenString)
// execute
def client = HttpClientBuilder.create().build()
def response = client.execute(post)
def bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()))
def authResponse = new JsonSlurper().parseText(bufferedReader.getText())

Related

C# WebClient.UploadData in Rails

I have a c# method that I'm trying to convert to ruby on rails . I'm using unirest but I think something is not working correctly. This is my C# method :
private static string HTTPPoster(string url, string prmSendData)
{
try
{
WebClient wUpload = new WebClient();
wUpload.Proxy = null;
Byte[] bPostArray = Encoding.UTF8.GetBytes(prmSendData);
Byte[] bResponse = wUpload.UploadData(url, "POST", bPostArray);
Char[] sReturnChars = Encoding.UTF8.GetChars(bResponse);
string sWebPage = new string(sReturnChars);
return sWebPage;
}
catch
{
return "-1";
}
}
And This is what I tried so far in rails with unirest :
def HTTPPoster(url)
xml = "My XML Goes Here"
byte_array = xml.bytes
headers = {}
headers['Content-Type'] = "application/json"
headers['Accept'] = "application/json"
response = Unirest.post(url,
headers: headers,
parameters: {
body: byte_array
})
puts "response #{response.body}"
if ![200,201].include?(response.code)
raise "Mblox Error: #{response.code}, #{response.body}"
end
end
If you also know other libraries that can achieve what I need please let me know.
I used Faraday gem and sent the data as xml and not as byte array. And now I am achieving want I wanted.
response = Faraday.post(url) do |req|
req.headers['Content-Type'] = "application/xml"
req.headers['Accept'] = "*/*"
req.headers['Accept-Encoding'] = "gzip, deflate, br"
req.body = xml
end

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

Post with Robospice and okHttp

I perform a POST using Robospice and okHttp :
public String loadDataFromNetwork() throws Exception {
uriBuilder = Uri.parse(url).buildUpon();
uri = new URI(uriBuilder.build().toString());
tmp = "user=" + user + "&password=" + pwd
HttpURLConnection connect = new OkUrlFactory(client).open(uri.toURL());
// Send post request
connect.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(connect.getOutputStream());
wr.writeBytes(tmp);
wr.flush();
wr.close();
// Read the response
in = connect.getInputStream();
}
Is there a better way to send a post (with Robospice/okHttp) ?
NB : my code is working fine, just want to know if it's correct or not...
The problem is that if I want to use the okHttp POST like that :
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url("https://api.github.com/markdown/raw")
.post(RequestBody.create(MEDIA_TYPE_MARKDOWN, parameters))
.build();
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
System.out.println(response.body().string());
with Robospice, RequestBody and newCall and isSuccessful cannot be resolved !
Do I have a solution to use okHttp post WITH Robospice ? (I know how to make a GET, but not a POST...)

Unable to implement Grails-jaxrs multipart file upload integration Test

I am using grails-jaxrs for exposing an api which accepts multipart/form-data..
#POST
#Consumes(MediaType.MULTIPART_FORM_DATA)
#Produces(['application/json'])
#Path('/addMessage')
ChatMessage addChatMessageWithAttachment(#Context HttpServletRequest req) {
log.debug "> addChatMessageWithAttachment"
def fileStores = []
def chatMessage
GrailsWebRequest request = WebUtils.retrieveGrailsWebRequest()
def params = request.getParams()
if (!(params.messageBody.length() > 0)) {
log.error("Empty message body")
throw new LocalisedException(ErrorCode.CHAT_MESSAGE_CREATE_FAILED)
}
}
The implementation is working properly as expected. I am able to send form-data (with file and other parameters successfully.
Now I am trying to implement integration test for above logic.
I am using IntegrationTestCase to achieve this.. so my code snippet is as below:
class ChatMessageResourceV1Tests extends IntegrationTestCase{
//other implementation and setup ommited
#Test
void "Create new chat message for event id - customer user"() {
def headers = ['Content-Type': 'multipart/form-data', 'Accept': 'application/json']
def data = "My message..."
def cm = new ChatMessage(messageBody: data)
def content = "{'eventId':'$event.id','messageBody':'My message...'}"
sendRequest("/api/v1/chatMessage/addMessage", 'POST', headers, content.bytes)
assertEquals(200, response.status)
}
}
When I run the test.. I can see the call reaches inside the API method.. But however, the parameter messageBody is coming as null and exception is being thrown.
I have tried every possible combination of test.. But no luck.
Any help would be appreciated.

Post request by ruby code and JAva code for Rails application

i am trying to call my Rails app using Ruby code .
I m having 2 tables .
Blogposts (id,name,slug,desc)
Comments (id,data,node_id,node_type)
I m trying to post a comment through my ruby code.
The Url for me is like
http://localhost:3000/api/blogs/comment.xml?slug=blogtitle-0&comment=aaaaaaaaaaaaaaa
I dont know how to write Ruby post code for this.
The one is tried is
require 'net/http'
require 'uri'
url = URI.parse('http://localhost:3000/api/blogs/comment.xml?slug=blogtitle-0')
req = Net::HTTP::Post.new(url.path)
req.basic_auth 'aruna', 'aruna'
req.set_form_data({'comment[data]'=>'aaaaaaaaaaaaaaa'}, ';')
res = Net::HTTP.new(url.host, url.port).start {|http| http.request(req) }
case res
when Net::HTTPSuccess, Net::HTTPRedirection
puts res.body
else
res.error!
end
end
Please help in fixing this
Edit: The same thing i am trying using Java using Jersey library file .
Here also i am not getting the result.
The one i tried in Java is,
blogBean = objBlogWrapper.postComment(slug,comment);
public BlogBean postComment(String slug, String comment) {
System.out.println(slug+""+comment);
// Create a multivalued map to store the parameters to be send in the REST call
MultivaluedMap<String, String> newBlogParam = new MultivaluedMapImpl();
// newBlogParam.add("blogpost[slug]", slug);
// newBlogParam.add("comment[data]", comment);
newBlogParam.add("slug", slug);
newBlogParam.add("comment", comment);
BlogBean blogBean = null;
try {
blogBean = webResource.path(ConfigurationUtil.POST_COMMENT).header(ConfigurationUtil.AUTHENTICATION_HEADER, authentication)
.type(MediaType.APPLICATION_FORM_URLENCODED_TYPE).accept(MediaType.APPLICATION_XML_TYPE).post(BlogBean.class, newBlogParam);
}catch (UniformInterfaceException uie) {
if (uie.getResponse().getStatus() == 401) {
System.out.println("Can not authenticate user "+ConfigurationUtil.userName +
". Please check your username/password and try again." );
} else {
System.out.println("Error when trying to talk to app. " +
"HTTP status code "+uie.getResponse().getStatus()+"returned. Finishing.");
}
return null;
} catch (ClientHandlerException che) {
System.out.println("Error when trying to talk toapp. Network issues? " +
"Please check the following message and try again later: "+che.getMessage());
return null;
}
return blogBean;
}
where my ConfigurationUtil.POST_COMMENT="api/blogs/comment.xml";
The above doesnt show me any error nor the comment is posted ..
Please give suggestions.
Here you go,
host, phost = ['http://localhost:3000', 'http://proxyhost:2521' ]
user, password = [ 'user_name' , 'password' ]
url, p_url = [URI.parse(host), URI.parse(phost)]
resp = nil
http = Net::HTTP.new(url.host, url.port, p_url.host, p_url.port)
req = Net::HTTP::Post.new(url.path)
req.basic_auth user, password
req.set_content_type 'application/xml'
req.body = 'your_request_body'
resp = http.start{|h| h.request(req)}
You may not need a proxy host at all. But just in case if you want your request proxied through, you can use that. The resp object will have your response.
With Faraday you just do
body_resp = Faraday.post 'http://localhost:3000/api/blogs/comment.xml', {:slug => 'blogtitle-0', :comment => 'aaaaaaaaaaaaaaa'}.body
Using some external gem can help because Net::Http class in Ruby is not the most simplest API.

Resources