On the Autoresponder I map a certain endpoint to respond to a certain URL request received.
I would like the endpoint receives the QUERY STRING and POST DATA, too.
I thought it was possible through the "REGEX:" wrapper in the rule, but it cannot capture any subexpression to pass to the mapped endpoint.
Can it be done through FiddlerScript? How to reference request and mapped endpoint?
This solution in C# allows to incercept the request to www.example-1.com and forward it to www.example-2.com, chaining possible query string and filling POSTDATA if given:
// match regex
string regex = "example-1.com/somepath/.*";
Regex rgx = new Regex(regex);
Match match = rgx.Match(oSession.fullUrl);
if (match.Success) {
// GET request -> replace the original URL with "https://www.example-2.com"
if (oSession.HTTPMethodIs("GET")) {
string qs = oSession.fullUrl.Split('?')[1];
oSession.fullUrl = oSession.fullUrl.Replace(oSession.fullUrl, "https://www.example-2.com/path?" + qs);
} else if (oSession.HTTPMethodIs("POST")) {
// Create an HTTP request to www.example-2.com and forward the request body saved above:
oSession.utilCreateResponseAndBypassServer();
var reqBody = oSession.GetRequestBodyAsString();
var data = Encoding.ASCII.GetBytes(reqBody);
var request = (HttpWebRequest)WebRequest.Create("https://plugvue.com/test/request-parser/api-write.php");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream()) {
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
}
}
It has to be put inside the OnBeforeRequest(Session oSession) handler.
Related
am faced with a challenge for some time now. I have a web service (asp.net web api), that consumes a certain api, after the consumption, my api will then send the consumed data to another external api. I use REST Sharp for my data serialization and request.
But anytime i send this request. I get a null result.
Anybody to help?
Sequel to my question above #igor, below is my code snippet
public object AccountOpening(JObject exRequest)
{
var Account = new AccountViewModel(exRequest.ToString());
Account.cifID = "null";
Account.AddrCategory = "Mailing";
Account.Country = "NG";
Account.HoldMailFlag = "N";
Account.PrefAddr = "Y";
Account.Language = "UK (English)";
Account.IsMinor = "N";
Account.IsCustNRE = "N";
Account.DefaultAddrType = "Mailing";
Account.Occupation = "OTH";
Account.PhoneEmailType = "CELLPH";
var serviceAPI = ConfigurationManager.AppSettings["RemoteAPI"];
var request = new RestSharp.Serializers.Newtonsoft.Json.RestRequest();
request.AddParameter("application/json", Account, ParameterType.RequestBody);
request.RequestFormat = DataFormat.Json;
request.Method = Method.POST;
request.JsonSerializer = new RestSharp.Serializers.JsonSerializer();
var client = new RestClient(serviceAPI);
IRestResponse resp = client.Post(request);
if (resp.IsSuccessful==true)
{
return Json(new {resp.Content });
}
}
I am trying pass contact id as a parameter to one of the webservices and get value to update in account object. But i am not able to set contact records ID field as a parameter in end point URL.
List<Contact> ContactUpdate = [SELECT id FROM Contact where Rep__c like 'CRM%'];
String ContactID;
HttpRequest req = new HttpRequest();
req.setTimeout(60000);
req.setHeader('Accept','*/*');
req.setHeader('Content-Type','application/json'); // Content Type
req.setMethod('GET');
for (Contact c : ContactUpdate)
{
ContactID = c.id;
req.setEndpoint('https://xxx/xxxx/xxxxx/xxx/xxx-lookup? ContactID= {! ContactID});
Http http = new Http();
HTTPResponse res = http.send(req);
System.debug(res.getBody());
JSONParser parser = JSON.createParser(res.getBody());
String GMMID;
while (parser.nextToken() != null) {
if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) &&
(parser.getText() == 'GCGMM')) {
// Get the value.
parser.nextToken();
// Compute the grand total price for all invoices.
GMMID = parser.gettext();
}
}
//ContactUpdate.IsFutureContext__c = true;
C.Group_ID__c = GMMID;
update c;
}
Could someone please guide me in adding variable as parameter in endpoint URL.
Try using the body and removing it from your endpoint.
String body = 'ContactID=' + contactID;
req.setbody(body);
I am using .NET to list the payments from my square account.
I am able to get a list of the payments, but to get the description field I have to go one level deeper and make http end point calls for each payment. This is time consuming.
Question: Can anyone provide me with a sample in Visual C# or Java to make batch calls for retrieving payments (using multiple payment id's)?
Your help is greatly appreciated.
Thanks,
Prashant
#Andrew - Here's what I am using, I am just not sure how to add the headers for batch payments retrieval.
string res = string.Empty;
string qs = string.Empty;
foreach (string s in parameters.Keys)
{
if (qs == string.Empty)
qs = "?";
else
qs += "&";
qs += s + "=" + parameters[s];
}
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(_connectUrl + "/" + command + qs); ///
request.Proxy = null;
request.Headers.Add("Authorization", "Bearer " + _accessToken);// ");
request.ContentType = "application/json";
request.Method = method; // "GET";
try { HttpWebResponse responseGet = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(responseGet.GetResponseStream());
StringBuilder output = new StringBuilder();
output.Append(reader.ReadToEnd());
responseGet.Close();
request = null;
return output.ToString();
}
catch (Exception exp)
Looks like I've been able to answer my own query.
We need to be able to send the following POST to the HTTP Endpoint
{"requests":[{"method":"GET","relative_path":"/v1/me/payments/<payment_id>","access_token":"XXXX","request_id":"1"},{"method":"GET","relative_path":"/v1/me/payments/<payment_id>","access_token":"XXXX","request_id":"2"}]}
the following code in .NET achieves the above
//Convert the body of request into a byte array
byte[] byteArray = Encoding.UTF8.GetBytes(body);
//Set the length
request.ContentLength = byteArray.Length;
//Write the body to the request by using a datastream
//This line never returns....
Stream datastream = request.GetRequestStream();
datastream.Write(byteArray, 0, byteArray.Length);
datastream.Close();
And that's all there is to it.
Hope this helps anyone is is set out to use the batch mode.
Thanks
I'm trying to integrate with an API that requires a PUT to update data:
Here's an example from them using curl:
curl --request PUT \
--user-agent "Your Client Name/1.0" \
--header "Content-Type: application/xml" \
--data-binary '<order><status_id>10</status_id></order>' \
https://www.example.com/api/v2/orders/101
However, I'd need to use JSON (they support that as well) using .NET MVC 3. Any idea on how I can do that?
I use the code below for GET successfully:
Order obj = Call<Order>(url, "GET");
private T Call<T>(string url, string methodType) where T : class {
T result;
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = methodType;
request.Accept = "application/json";
request.ContentType = "application/json";
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
using (StreamReader reader = new StreamReader(response.GetResponseStream())) {
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
string jsonData = reader.ReadToEnd();
result = (T)jsSerializer.Deserialize<T>(jsonData);
}
return result;
}
However, can I issue a PUT using a similar method?
Order obj = Call<Order>(url, "PUT");
If so, where do I put the data that's required in "data-binary"?
Well, here's a possible point of origin - untested; written straight into the browser; not production code; assumes that the PUT call both sends and receives the same object type (which is probably not the case)...
The main addition is that you need to supply the request's ContentLength, and you need to write the serialized JSON object to the request stream, which you'll get by calling HttpWebRequest::GetRequestStream(). It's the same approach as when POSTing.
private T Call<T>(string url, string methodType, T data) where T: class
{
T result;
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = methodType;
request.ContentType = "application/json";
request.Accept = "application/json";
if (methodType == "PUT" || methodType == "POST")
{
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
string jsonData = jsSerializer.Serialize(data);
byte[] arrData = Encoding.UTF8.GetBytes(jsonData);
request.ContentLength = arrData.Length;
using (Stream dataStream = request.GetRequestStream())
{
dataStream.Write(arrData, 0, arrData.Length);
}
}
// Note: You may not need to parse any response content,
// or it may be a different class
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
using (StreamReader reader
= new StreamReader(response.GetResponseStream()))
{
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
string jsonData = reader.ReadToEnd();
result = (T)jsSerializer.Deserialize<T>(jsonData);
}
}
return result;
}
I am creating a program that auto login into a website using forms authentication. When ever I call my method to connect to the website, it returns me a empty document text. However, if I call the same method a second time, it works perfectly.
Here is my code :
//perform authentication and stores the session in the cookiecontainer
private void loginToSite()
{
// prepare the web page we will be asking for
request = (HttpWebRequest)
WebRequest.Create(#"http://diary.com/notes/my_journal");
request.KeepAlive = true;
//========================================
//start of forms authentication parameters
//========================================
string authInfo = username + ":" + password;
authInfo = Convert.ToBase64String(Encoding.Default.GetBytes(authInfo));
request.Headers["Authorization"] = "Basic " + authInfo;
//========================================
//end of forms authentication parameters
//========================================
request.ContentType = "text/html";
request.Method = "GET";
request.AllowAutoRedirect = true;
request.Referer = #"http://diary.com/";
request.CookieContainer = new CookieContainer();
// execute the request
HttpWebResponse response = (HttpWebResponse)
request.GetResponse();
// we will read data via the response stream
Stream resStream = response.GetResponseStream();
container = request.CookieContainer;
//assign the http content to myWB for manipulation
//myWB is a WebBrowser object that have been declared
myWB.DocumentStream = resStream;
//prevent script errors from popping up
myWB.ScriptErrorsSuppressed = true;
MessageBox.Show(myWB.DocumentText);
}