Groovy rest client without libraries - rest

I am using a rest client to do Post
My code is
def postRequest() {
def message = "{ \"fields\": { \"project\": { \"id\": \"001\" },\"summary\": \"Test Issue For Jira Integration\",\"description\": \"Creating of an issue for for projects and issue types using the REST API\", \"issuetype\": { \"id\": \"5\" } }}"
// POST
def post = new URL("https://jira/rest/api/latest/issue").openConnection();
//def message = '{"message":"this is a message"}'
post.setRequestMethod("POST")
String userpass = "user:pass" ;
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userpass.getBytes()));
post.setRequestProperty ("Authorization", basicAuth);
post.setDoOutput(true)
post.setRequestProperty("Content-Type", "application/json")
post.getOutputStream().write(message.getBytes("UTF-8"));
def postRC = post.getResponseCode();
println(postRC);
if(postRC.equals(201)) {
println(post.getInputStream().getText());
}else
{
println(post.getInputStream().getText());
print(postRC)
}
}
I am getting 400 error code , where its getting wrong
I am successfully able to do the get request with URL

400 = bad request.
it means server tried to validate your post data and it's wrong.
usually this response contains body with explanation...
for 400+ status codes the body comes through getErrorStream() and not through getInputStream()
So, I would do it like this:
def postRequest(url, message) {
def post = new URL(url).openConnection();
//def message = '{"message":"this is a message"}'
post.setRequestMethod("POST")
String userpass = "user:pass" ;
String basicAuth = "Basic " + userpass.getBytes("UTF-8").encodeBase64()
post.setRequestProperty("Authorization", basicAuth);
post.setRequestProperty("Content-Type", "application/json")
post.setDoOutput(true)
if( !(message instanceof String) )message = new groovy.json.JsonBuilder(message).toPrettyString()
post.getOutputStream().write(message.getBytes("UTF-8"))
def response=[:]
response.code = post.getResponseCode()
response.message = post.getResponseMessage()
if( response.code>=400 ){
try{
response.body = post.getErrorStream()?.getText("UTF-8")
}catch(e){}
}else{
response.body = post.getInputStream()?.getText("UTF-8")
}
assert response.code in [200,201] : "http call failure ${response.code}: ${ response.body ?: response.message }"
return response
}
def msg = [
fields: [
project : [ id: "001" ],
summary : "Test Issue For Jira Integration",
description : "Creating of an issue for for projects and issue types using the REST API",
issuetype : [ id: "5" ]
]
]
def r = postRequest("http://httpbin.org/post", msg)
println r

The issue was related to certificate , I have to bypass the certificate validation and its working fine. Since both the application are under same network and behind same company's firewall , I have bypass the certificate validations.
Adding the skipping certificate validation part to the above code is working for me

Related

How to call Microsoft Graph REST API with groovy-wslite

I am trying to call Microsoft Graph API on groovy script using Java libraries. However, even though partly success, I still have some serious issues using it within my current project, so I think about trying to call the the REST API using groovy-wslite.
This is my current code for getting access token:
def authorizeHost = "https://login.microsoftonline.com"
def authorizePath = "/${azureSetting.getTenantID()}/oauth2/v2.0/authorize?"
try {
RESTClient client = new RESTClient(authorizeHost)
def params = [
"client_id":azureSetting.getClientID(),
"scope": "https://graph.microsoft.com/.default",
"response_type": "code"
]
def response = client.post(
path: authorizePath,
)
{
type ContentType.JSON
json params
}
LOGGER.info("Success: " + (response.statusCode == 200));
LOGGER.info("Output: (" + response.contentType + ") " + response.text);
} catch (RESTClientException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
LOGGER.info("Error: " + sw.toString());
}
The response from the log:
AADSTS900144: The request body must contain the following parameter: 'client_id'.
How can I change the above code, so that Microsoft Graph REST API can recognize my sending content and send back the access token.
UPDATE: After trying around, I found out that the body os post method should be as below:
type "application/x-www-form-urlencoded"
urlenc client_id: azureSetting.getClientID(),
scope: "https://graph.microsoft.com/.default",
response_type: "code"
according to doc https://learn.microsoft.com/en-us/graph/auth-v2-user#token-request your request should have Content-Type: application/x-www-form-urlencoded
you are trying to send json instead
here is your code but pointing to a test httpbin.org server and it could show what exactly you are sending to server
there is a minor change: ContentType.JSON -> ContentType.URLENC
#Grab(group='com.github.groovy-wslite', module='groovy-wslite', version='1.1.3', transitive=false)
import wslite.rest.*
//just for test
def azureSetting = [ getClientID:{-> "12345"} ]
def LOGGER = [info:{x-> println x}]
//redefined host and url
def authorizeHost = "HTTP://httpbin.org"
def authorizePath = "/post"
try {
RESTClient client = new RESTClient(authorizeHost)
def params = [
"client_id":azureSetting.getClientID(),
"scope": "https://graph.microsoft.com/.default",
"response_type": "code"
]
def response = client.post(
path: authorizePath,
)
{
type ContentType.URLENC // <-- THE ONLY CHANGE IN YOUR CODE
json params
}
LOGGER.info("Success: " + (response.statusCode == 200));
LOGGER.info("Output: (" + response.contentType + ") " + response.text);
} catch (RESTClientException e) {
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
LOGGER.info("Error: " + sw.toString());
}

facebook messenger curl request returns <Response [400]>

I am new to the messenger API, I want to send a message using a curl post request, this is my code:
import requests
ACCESS_TOKEN = an Active access token
fb_url = "https://graph.facebook.com/v10.0/me/messages"
data = {
'recipient': '{"id":4098757906843152}',
"message": {
"text": "hello, world!"
},
"messaging_type": "MESSAGE_TAG",
"tag": "ACCOUNT_UPDATE"
}
params = {'access_token': ACCESS_TOKEN}
resp = requests.post(fb_url, params=params, data=data)
print(resp)
unfortunately, I got this message <Response [400]>
any help would be appreciated
You need to change data to json.
See https://stackoverflow.com/a/26344315/603756
Starting with Requests version 2.4.2, you can use the json= parameter (which takes a dictionary) instead of data= (which takes a string) in the call
import requests
ACCESS_TOKEN = '<access_token>'
fb_url = 'https://graph.facebook.com/v10.0/me/messages'
data = {
'recipient': '{"id":<psid>}',
"message": {
"text": "hello, world!"
}
}
params = {'access_token': ACCESS_TOKEN}
resp = requests.post(fb_url, json=data, params=params)
print(resp)

How to use HttpWebRequest GET method in Twitter API [duplicate]

I am trying to execute a simple "request body search" on Elasticsearch like the following example but using .NET instead of curl
$ curl -XGET 'http://localhost:9200/twitter/tweet/_search' -d '{
"query" : {
"term" : { "user" : "kimchy" }
}
}
'
Below is my .NET code.
var uri = "http://localhost:9200/myindex/_search";
var json = "{ \"query\" : { \"term\" : { \"user\" : \"kimchy\" } } }";
var request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(uri);
request.ContentType = "text/json";
request.Method = "GET";
var responseString = string.Empty;
using (var streamWriter = new System.IO.StreamWriter(request.GetRequestStream()))
{
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
var response = (System.Net.HttpWebResponse)request.GetResponse();
using (var streamReader = new System.IO.StreamReader(response.GetResponseStream()))
{
responseString = streamReader.ReadToEnd();
}
}
However, I am getting the following error.
Cannot send a content-body with this verb-type.
...
Exception Details: System.Net.ProtocolViolationException: Cannot send a content-body with this verb-type.
...
Line 54: using (var streamWriter = new System.IO.StreamWriter(request.GetRequestStream()))
Is there any way I can send a content-body with a GET request using standard .NET classes. Or is there a workaround?
Changing the Method to POST is a workaround.
request.Method = "POST";
MSDN states that a ProtocolViolationException will be thrown if the GetResponseStream() method is called with a GET or HEAD method.

SOAP Request to Wemo switch from Pebble returns status 500

Been trying to write a pebble app for wemo switches, currently this is the code i'm using:
function WemoRequest(callback) {
if (SOAPData === false || SOAPData === undefined) {
console.log("Invalid SOAP data: " + JSON.stringify(SOAPData));
return;
}
var url = "http://192.168.1.230:49153/upnp/control/basicevent1";
try {
var request = new XMLHttpRequest();
request.open("POST", url, false);
request.setRequestHeader("SOAPAction", "urn:Belkin:service:basicevent:1#GetBinaryState");
request.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status === 200 && callback) {
callback(request, SOAPData);
}else{console.log("Status: "+request.status + " State: "+request.readyState+" Callback: "+callback);}
};
var packet = '<?xml version="1.0" encoding="utf-8"?>'+
'<s:Envelope xmls:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">'+
'<s:Body>'+
'<u:GetBinaryState xmlns:u="urn:Belkin:service:basicevent:1"></u:GetBinaryState>'+
'</s:Body>'+
'</s:Envelope>';
request.send(packet);
} catch (error) {
console.log("Error in XMLHttpRequest: " + error);
}}
I currently get status 500 from OnReadyStateChange and have no idea what I'm doing wrong. If this isn't enough code, app code is available here:https://github.com/dmf444/Webble
So...I know this is from 4 years ago lol, but I found this during a google search and just found the answer, so I figured I would respond for that reason: I think your header just needs an extra set of quotes around "urn:Belkin:service:basicevent:1#SetBinaryState" so that the string specifying the soapaction literally starts and ends with quotes.
I'm working in Python (because that's what all the kids seem to be doing these days), but I too was getting the 500 error until I made a very subtle change (the single quote marks around my double quotes) and almost cried tears of joy when my light turned off:
"SOAPACTION": '"urn:Belkin:service:basicevent:1#SetBinaryState"'
So here's the working version of the code (in Python lol):
import http.client
#Variables (value=on/off, ipaddress=address of your wemo)
value = 0 #1=ON, 0=OFF
ipAddress = "192.168.0.108"
#Build the SOAP Envelope (data)
data = '<?xml version="1.0" encoding="utf-8"?><s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><s:Body><u:SetBinaryState xmlns:u="urn:Belkin:service:basicevent:1"><BinaryState>' + str(value) + '</BinaryState></u:SetBinaryState></s:Body></s:Envelope>'
#Build the Header (headers)
headers = {"Content-type" : 'text/xml; charset="utf-8"', "SOAPACTION": '"urn:Belkin:service:basicevent:1#SetBinaryState"', "Content-Length": len(data)}
#Send request and check response data (resp_data)
conn = http.client.HTTPConnection(ipAddress, 49153)
conn.request("POST", "/upnp/control/basicevent1", data, headers)
response = conn.getresponse()
resp_data = response.read()
if response.status == 200:
conn.close()
print("SUCCESS!")
elif response.status == 403:
print("ERROR: 403 (FORBIDDEN)")
else:
print("ERROR: " + str(response.status))

Getting 500 error while creating vertex using Rest API

I am writing a SSIS script component for importing data into orientdb using RestAPI but i am getting error 500. Please i am stuck here. Is there anyone who can help me with this. I am using version 2.1.7 community edition.
Here is my code so far.
Uri address = new Uri("http://localhost:2480//command/SQ-DB/sql/");
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
request.Method = "POST";
request.Accept = "application/json; charset=UTF-8";
request.ContentType = "application/json";
string username = "root";
string password = "***";
String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
request.Headers.Add("Authorization", "Basic " + encoded);
StringBuilder data = new StringBuilder();
// string link = "{\"statements\" : [ {\"statement\" : \"CREATE ( company: Accounts { Name:" + Row.companyname + "} ) RETURN company\"} ]}";
string link= "CREATE VERTEX Contacts CONTENT { 'name' : "+ Row.fullname+", 'Email' : "+ Row.emailaddress1+", 'Phone' : "+ Row.telephone1 + ", 'ContactId' : "+ Row.contactid+", 'City' : "+Row.address1city+"}" ;
data.Append(HttpUtility.UrlEncode(link));
// Create a byte array of the data we want to send
byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());
// Set the content length in the request headers
request.ContentLength = byteData.Length;
request.Headers.Add("Accept-Encoding", "gzip,deflate");
using (Stream postStream = request.GetRequestStream())
{
postStream.Write(byteData, 0, byteData.Length);
}
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
// Console application output
Console.WriteLine(reader.ReadToEnd());
}
It will be a great help if anyone can point the issue. Thank you