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

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.

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());
}

Groovy rest client without libraries

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

GetResponseAsync timeout after a few POST request

i'm making a POST request in C# like this:
var request = WebRequest.Create("http://xxx.xxx.xxx.xxx:8080/xxx/obj/data/xxx/commands/GET");
request.ContentType = "application/json";
((HttpWebRequest)request).Accept = "application/json";
request.Headers.Add(HttpRequestHeader.AcceptLanguage, "en");
NetworkCredential myNetworkCredentials = new NetworkCredential("myUser", "MyPass");
CredentialCache myCredentialCache = new CredentialCache
{
{ link, "Basic", myNetworkCredentials }
};
request.Credentials = myCredentialCache;
request.PreAuthenticate = true;
request.Method = "POST";
await request.GetResponseAsync();
When i'm using Postman to check the response, it's all ok, it works every time i send the request.
But programmatically, after 7-8 times, the await request.GetResponseAsync(); is giving me a Exception, "The Operation has timed out".
I don't know how to check this, in postman it's all ok, but in the app it failed after a few test. What can i do?
By default, you have only 10 Connection Limit when you start the App. So you need to setup this in the Uri for your request
ServicePoint sp = ServicePointManager.FindServicePoint(uri);
sp.ConnectionLimit = 1000;
ServicePointManager.DefaultConnectionLimit = 1000;

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

UrlFetchApp Authentication failed Freshbooks

So I am trying to communicate with the freshbooks api by making the sample request detailed on the developers page of freshbooks (http://developers.freshbooks.com/). We are doing token-based authentication as opposed to using OAuth.
I have my code logging the responses to my requests in a spreadsheet. The responses it has been logging are as follows:
<?xml version="1.0" encoding="utf-8"?>
<response xmlns="http://www.freshbooks.com/api/" status="fail">
<error>Authentication failed.</error>
<code>20010</code>
</response>
I have been able to authenticate when using a curl command in console, but not when running the script. Below is the code I used. Left out the logging to spreadsheet part and our specific url and authToken:
// Sample function to call into an API using basic HTTP auth
function freshbooksTest () {
var url = ;
var authToken = ;
var unamepass =authToken+":X";
var digestfull = "Basic "+unamepass;
var payload = '<request method="system.current"></request>';
var options =
{
"method" : "post",
"muteHttpExceptions": true,
"headers" : {"Authorization": digestfull},
"payload" : payload
};
var response = UrlFetchApp.fetch(url, options);
var xml = response.getContentText();
}
I have checked out threads where people are having similar problems, but the solutions were either not applicable to my situation, or have already been tried. Any suggestions are welcome.
Not specifically familiar with UrlFetchApp, but if it doesn't do it for you, you'll need to Base64 encode digestfull before you send it in the header.
Looks like you need to base 64 encode your auth token. Code should look like this:
function freshbooksTest () {
var url = ;
var authToken = ;
var unamepass = authToken+":X";
var digestfull = "Basic "+ Utilities.base64Encode(unamepass);
var payload = '<request method="system.current"></request>';
var options =
{
"method" : "post",
"muteHttpExceptions": true,
"headers" : {"Authorization": digestfull},
"payload" : payload
};
var response = UrlFetchApp.fetch(url, options);
var xml = response.getContentText();
}