I'm trying to transition issues via the API using .NET but I'm consistently getting a 400 error back. I'm wondering if anyone can see anything obvious that I'm doing wrong?
Code:
string example = #"{
""id"": ""221""
}";
string ticketjson = JsonConvert.SerializeObject(example);
string postUrl = "https://myurl/rest/api/2/issue/" + issueKey + "/transitions";
System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
client.BaseAddress = new System.Uri(postUrl);
byte[] cred = UTF8Encoding.UTF8.GetBytes("username:pwd");
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(cred));
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
var content = new StringContent(ticketjson, Encoding.UTF8, "application/json");
var response = client.PostAsync(postUrl, content).Result;
if (response.IsSuccessStatusCode)
{
string result = response.Content.ReadAsStringAsync().Result;
return result;
}
else
{
unauth.Text = "There has been a problem submitting your comment. Please try again.";
return response.StatusCode.ToString();
}
The transition exists and when I go to the postUrl I can see it:
Any help would be appreciated!
I have error requests. I still don't know where to invoke request and how to fetch response. Where do I set API key?
var initialize = new Google.Apis.Services.BaseClientService.Initializer();
initialize.ApiKey = "key";
var speech = new Google.Apis.Speech.v1.SpeechService(new Google.Apis.Services.BaseClientService.Initializer {
});
var recognizeReq = new Google.Apis.Speech.v1.Data.RecognizeRequest();
var recognitionConf = new Google.Apis.Speech.v1.Data.RecognitionConfig();
recognitionConf.LanguageCode = "pl-PL";
recognitionConf.SampleRateHertz = 16000;
recognitionConf.Encoding = "FLAC";
recogniseReq.Config = recognitionConf;
var aud = new Google.Apis.Speech.v1.Data.RecognitionAudio();
string path1 = #"c:\output.flac";
//var bytesAudio = File.ReadAllBytes(path1);
aud.Uri = path1;
recognizeReq.Audio = aud;
var variable = speech.Speech.Recognize(recogniseReq);
variable.Key = "key";
//variable.OauthToken =
variable.Execute();
Google.Apis.Speech.v1.Data.RecognizeResponse resp = new Google.Apis.Speech.v1.Data.RecognizeResponse();
var lista = resp.Results;
I change software and now I use Google.Cloud.Speech.V1 library
I managed to save voice using NAudio
and I tried to send continuos request to cloud, but it doesn't work
'''
waveFile.Write(e.Buffer, 0, e.BytesRecorded);
waveFile.Flush();
audio5 = RecognitionAudio.FromBytes(e.Buffer);
var result = client.LongRunningRecognizeAsync(config, audio5);
'''
This solves problem.
problem with buffer is for a longer time.
I get into trap like others.
found solution in dispute about bug (from Google of corse ;) )
https://github.com/GoogleCloudPlatform/dotnet-docs-samples/blob/95b32e683ba534883b8a7f3c979deee101ba3678/speech/api/Recognize/InfiniteStreaming.cs
The following code by #Nick Rupley works well, but, I need also to pass parameters as POST. How do we pass POST parameters?
from java.net.URL
var url = new java.net.URL('http://localhost/myphpscript.php');
var conn = url.openConnection();
var is = conn.getInputStream();
try {
var result = org.apache.commons.io.IOUtils.toString(is, 'UTF-8');
} finally {
is.close();
}
2 Parameters to pass: firstname="John" and lastname="Smith"
Thanks
This will POST with MIME type application/x-www-form-urlencoded. It is using apache httpclient, which is already included with mirth, as it is used internally by the HTTP Sender connector, as well as some other functionality. Other solutions may require you to download jars and add library resources.
Closer is part of Google Guava, which is also already included with mirth.
Check comments where Rhino javascript allows for simplified code compared to direct Java conversion.
It wouldn't be a bad idea to wrap all of this up in a code template function.
var result;
// Using block level Java class imports
with (JavaImporter(
org.apache.commons.io.IOUtils,
org.apache.http.client.methods.HttpPost,
org.apache.http.client.entity.UrlEncodedFormEntity,
org.apache.http.impl.client.HttpClients,
org.apache.http.message.BasicNameValuePair,
com.google.common.io.Closer))
{
var closer = Closer.create();
try {
var httpclient = closer.register(HttpClients.createDefault());
var httpPost = new HttpPost('http://localhost:9919/myphpscript.php');
// javascript array as java List
var postParameters = [
new BasicNameValuePair("firstname", "John"),
new BasicNameValuePair("lastname", "Smith")
];
// Rhino JavaBean access to set property
// Same as httpPost.setEntity(new UrlEncodedFormEntity(postParameters, "UTF-8"));
httpPost.entity = new UrlEncodedFormEntity(postParameters, "UTF-8");
var response = closer.register(httpclient.execute(httpPost));
// Rhino JavaBean access to get properties
// Same as var is = response.getEntity().getContent();
var is = closer.register(response.entity.content);
result = IOUtils.toString(is, 'UTF-8');
} finally {
closer.close();
}
}
logger.info(result);
Following is a complete working HTTP POST request solution tested in Mirth 3.9.1
importPackage(Packages.org.apache.http.client);
importPackage(Packages.org.apache.http.client.methods);
importPackage(Packages.org.apache.http.impl.client);
importPackage(Packages.org.apache.http.message);
importPackage(Packages.org.apache.http.client.entity);
importPackage(Packages.org.apache.http.entity);
importPackage(Packages.org.apache.http.util);
var httpclient = HttpClients.createDefault();
var httpPost = new HttpPost("http://localhost/test/");
var httpGet = new HttpGet("http://httpbin.org/get");
// FIll in each of the fields below by entering your values between the ""'s
var authJSON = {
"userName": "username",
"password": "password",
};
var contentStr =JSON.stringify(authJSON);
//logger.info("JSON String: "+contentStr);
httpPost.setEntity(new StringEntity(contentStr,ContentType.APPLICATION_JSON,"UTF-8"));
httpPost.setHeader('Content-Type', 'application/json');
httpPost.setHeader("Accept", "application/json");
// Execute the HTTP POST
var resp;
try {
// Get the response
resp = httpclient.execute(httpPost);
var statusCode = resp.getStatusLine().getStatusCode();
var entity = resp.getEntity();
var responseString = EntityUtils.toString(entity, "UTF-8");
var authHeader = resp.getFirstHeader("Authorization");
// logger.info("Key : " + authHeader.getName()+" ,Value : " + authHeader.getValue());
// Save off the response and status code to Channel Maps for any potential troubleshooting
channelMap.put("responseString", responseString);
channelMap.put("statusCode", statusCode);
// Parse the JSON response
var responseJson = JSON.parse(responseString);
// If an error is returned, manually throw an exception
// Else save the token to a channel map for use later in the processing
if (statusCode >= 300) {
throw(responseString);
} else {
logger.info("Token: "+ authHeader.getValue());
channelMap.put("token", authHeader.getValue());
}
} catch (err) {
logger.debug(err)
throw(err);
} finally {
resp.close();
}
This linke + above answers helped me to come up with a solution
https://help.datica.com/hc/en-us/articles/115005322946-Advanced-Mirth-Functionality
There are plenty of libraries that can help you with URI building in Java. You can find them below. But if you want to stay in Javascript just add your parameters manually than create it.
function addParam(uri, appendQuery) {
if (appendQuery != null) {
uri += "?" + appendQuery;
}
return uri;
}
var newUri = addParam('http://localhost/myphpscript.php', 'firstname="John"');
var url = new java.net.URL(newUri);
Java EE 7
import javax.ws.rs.core.UriBuilder;
...
return UriBuilder.fromUri(url).queryParam(key, value).build();
org.apache.httpcomponents:httpclient:4.5.2
import org.apache.http.client.utils.URIBuilder;
...
return new URIBuilder(url).addParameter(key, value).build();
org.springframework:spring-web:4.2.5.RELEASE
import org.springframework.web.util.UriComponentsBuilder;
...
return UriComponentsBuilder.fromUriString(url).queryParam(key, value).build().toUri();
There are multiple ways to provide http client connection with java. Since your question is specific to java.net.URL I will stick to that.
Basically you can pass parameters as POST, GET, PUT, DELETE using .setRequestMethod this will be used along with new java.net.URL(ur-destination-url).openConnection();
Here is the complete code I've using javascript in Mirth using the same java.net.URL use this it will be helpful. It worked well for me.
do {
try {
// Assuming your writing this in the destination Javascript writer
var data = connectorMessage.getEncodedData();
//Destination URL
destURL = “https://Your-api-that-needs-to-be-connected.com”;
//URL
var url = new java.net.URL(destURL);
var conn = url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
enter code here
conn.setRequestProperty (“Authorization”, globalMap.get(‘UniversalToken’));
conn.setRequestMethod(“DELETE”); // this can be post or put or get or patch
conn.setRequestProperty(“Content-length”, data.length());
conn.setRequestProperty(“Content-type”, “application/json”);
var outStream = conn.getOutputStream();
var outWriter = new java.io.OutputStreamWriter(outStream);
outWriter.write(data);
outWriter.close();
// Get response Code (200, 500 etc.)
var respCode = conn.getResponseCode();
if (respCode != 200) {
// Write error to error folder
var stringData = response.toString() + “\n”;
FileUtil.write(“C:/Outbox/Errors/” + $(“originalFilename”) + “.ERROR_RESPONSE”, false, stringData);
// Return Error to Mirth to move the file to the error folder
return ERROR;
}
errorCond = “false”;
break;
}
catch(err) {
channelMap.put(“RESPONSE”, err);
responseMap.put(“WEBSVC”, ResponseFactory.getErrorResponse(err))
throw(err);
// Can return ERROR, QUEUED, SENT
// This re-queues the message on a fatal error. I”m doing this since any fatal message may be
// caused by HTTPS connect errors etc. The message will be re-queued
return QUEUED; // Re-queue the message
java.lang.Thread.sleep(6000); // 6 seconds * 10
errorCond = “true”;
}
}
while (errorCond == “true”);
I am using Microsoft Graph SDK to upload file in chunks in OneDrive. I am using below code to upload the file:
try
{
GraphServiceClient graphClient = this.GetGraphServiceClient(accessToken);
string fileName = Path.GetFileName(srcFilePath);
using (var fileContentStream = System.IO.File.Open(srcFilePath, System.IO.FileMode.Open))
{
var uploadSession = await graphClient.Me.Drive.Root.ItemWithPath(fileName).CreateUploadSession().Request().PostAsync();
var maxChunkSize = 5 * 1024 * 1024;
var provider = new ChunkedUploadProvider(uploadSession, graphClient, fileContentStream, maxChunkSize);
var chunkRequests = provider.GetUploadChunkRequests();
var readBuffer = new byte[maxChunkSize];
var trackedExceptions = new List<Exception>();
Microsoft.Graph.DriveItem itemResult = null;
foreach (var request in chunkRequests)
{
var result = await provider.GetChunkRequestResponseAsync(request, readBuffer, trackedExceptions);
if (result.UploadSucceeded)
{
itemResult = result.ItemResponse;
}
}
}
}
catch (Microsoft.Graph.ServiceException e)
{
}
catch (Exception ex)
{
}
The above code works fine with normal file names. However, when I am trying to upload a file with name as Test#123.pdf, "Object reference not set to an object" exception is thrown at line var provider = new ChunkedUploadProvider(uploadSession, graphClient, fileContentStream, maxChunkSize); Please see below screenshot:
Is this a limitation of OneDrive SDK, or am I not passing the parameters correctly?
The # sign has a special meaning in a URL. Before you can use it, you'll need to URL Encode the file name: Test%23123.pdf.
I am trying to make a request to a REST method and recieve the data in XML but this all goes well but when i want to use credentials for a method, because for this method you need to give credentials.
https://handshake:16a144bc5f480692d5c8d926068d2db5#rest-api.pay.nl/v2/Transaction/getStatus/xml/?orderId=236750347X6d2ee7
But when i use this one in the browser it work but this is not working from my controller.
//
// GET: /Home/Succes
public ActionResult Succes(string orderId)
{
string token = PaymentCalls.Login();
ViewBag.Token = token;
string _URL = "https://handshake:" + token + "#rest-api.pay.nl/v2/Transaction/getStatus/xml/?orderId=" + orderId;
NetworkCredential cr = new NetworkCredential("handshake", token);
XDocument doc = XDocument.Load(_URL);
var output = from feed in doc.Descendants("data")
select new Status
{
amount = feed.Element("amount").Value,
consumerAccountNumber = feed.Element("consumerAccountNumber").Value,
consumerCity = feed.Element("consumerCity").Value,
consumerEmail = feed.Element("consumerEmail").Value,
consumerName = feed.Element("consumerName").Value,
consumerZipcode = feed.Element("consumerZipcode").Value,
countryCode = feed.Element("countrCode").Value,
entranceCode = feed.Element("entranceCode").Value,
ipAddress = feed.Element("ipAddress").Value,
orderId = feed.Element("orderId").Value,
statsAdded = feed.Element("statsAdded").Value,
paymentSessionId = feed.Element("paymentSessionId").Value,
result = feed.Element("result").Value,
statusAction = feed.Element("statusAction").Value
};
return View(output);
So when we call this controller we get an 401 error but using the same url in the browser works. So i dont know but how can i set to pass credentials or something?