I'm trying to create an issue in JIRA cloud using c# and the REST API,
I get the 400 error (bad rquest), I dont know what I'm doing wrong !
This is My functions
public static string PostJsonRequest(string endpoint, string userid, string password, string json)
{
// Create string to hold JSON response
string jsonResponse = string.Empty;
using (var client = new WebClient())
{
try
{
client.Encoding = System.Text.Encoding.UTF8;
client.Headers.Set("Authorization", "Basic " + GetEncodedCredentials(userid, password));
client.Headers.Add("Content-Type: application/json");
client.Headers.Add("Accept", "application/json");
var uri = new Uri(endpoint);
var response = client.UploadString(uri, "POST", json);
jsonResponse = response;
}
catch (WebException ex)
{
// Http Error
if (ex.Status == WebExceptionStatus.ProtocolError)
{
HttpWebResponse wrsp = (HttpWebResponse)ex.Response;
var statusCode = (int)wrsp.StatusCode;
var msg = wrsp.StatusDescription;
// throw new SmtpException(statusCode, msg);
}
else
{
// throw new HttpException(500, ex.Message);
}
}
}
return jsonResponse;
}
And this is my JSON
string json = #"{
'fields':
{
'project':
{
'key':'IS'
},
'summary':'REST Test',
'issuetype':
{
'name':'Bug'
},
}
}";
string Url = "https://XXXXXX.atlassian.net/rest/api/2/issue/";
Any Ideas on what I'm doing wrong ?
Related
Good day Guys,
I am trying to Use an SMS API. Everything looks fine from my end but the SMS is not delivering. If i use the URL directly on Browser, it executes.
Or is anything wrong with how i built the string?
Below is the code.
Please Note tht cbo.Title is a comobox, txtFirstname is a Textbox.
public void NewText()
{
string username = "something#gmail.com";
string password = "Password";
string urlStr;
string message=" Dear " + cbo_Title.Text + " " + txt_FirstName.Text + ", Your New Savings Account Number is " + Account_No + ".Welcome to AGENTKUNLE Global Services. Your Future is Our Priority ";
string sender = "AGENTKUNLE";
string recipient=txt_Phone.Text;
urlStr = "https://portal.nigeriabulksms.com/api/?username="+username+"+password="+password+"+sender="+sender+"+message="+message+"+ mobiles="+recipient;
Uri success = new Uri(urlStr);
}
private string SendSms(string apiUrl)
{
var targetUri = new Uri(apiUrl);
var webRequest = (HttpWebRequest) WebRequest.Create(targetUri);
webRequest.Method = WebRequestMethods.Http.Get;
try
{
string webResponse;
using (var getresponse = (HttpWebResponse) webRequest.GetResponse())
{
var stream = getresponse.GetResponseStream();
if (stream != null)
using (var reader = new StreamReader(stream))
{
webResponse = reader.ReadToEnd();
reader.Close();
}
else
webResponse = null;
getresponse.Close();
}
if (!string.IsNullOrEmpty(webResponse?.Trim()))
return webResponse.Trim();
}
catch (WebException ex)
{
ErrorHelper.Log(ex);
}
catch (Exception ex)
{
ErrorHelper.Log(ex);
}
finally
{
webRequest.Abort();
}
return null;
}
You never make a request.
The Uri object is just a container for the uri (see Microsoft Docs).
Check out the HttpClient class if you want to send a request.
I am trying to ReplyAll to email with Outlook 365 API. Following this tutorial. As per tutorial to ReplyAll we just need to input Commnet but when I try to do that it's giving Bad Request error -
"error": {
"code": "ErrorInvalidRecipients",
"message": "At least one recipient isn't valid., A message can't be sent because it contains no recipients."
}
I am trying to do this with below method.
public string EmailReplyAll(AuthenticationResult result, string uriString, string msgBody)
{
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, uriString);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
EmailReplyAll replyAll = new EmailReplyAll();
replyAll.MsgBody = msgBody;
var jsonData = JsonConvert.SerializeObject(msgBody);
var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
HttpResponseMessage response = httpClient.PostAsync(request.ToString(),content).Result;
if (!response.IsSuccessStatusCode)
throw new WebException(response.StatusCode.ToString() + ": " + response.ReasonPhrase);
uriString = response.Content.ReadAsStringAsync().Result;
return uriString;
}
Could someone please point me where I am doing wrong. I'm trying this with WPF.
Here is what I figured out and working for me.
EmailReplyAll class
public class EmailReplyAll
{
public string Comment { get; set; }
}
The URI string -
var uriString = String.Format(CultureInfo.InvariantCulture, "{0}api/{1}/me/messages/{2}/replyall", graphApiEndpoint, graphApiVersion, emailId);
//emailId is id of email e.g - AAMkADBjMGZiZGFACAAC8Emr9AAA=
EmailReplyAll method -
public string EmailReplyAll(AuthenticationResult result, string uriString, string msgBody)
{
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
EmailReplyAll replyAll = new EmailReplyAll();
replyAll.Comment = msgBody;
var jsonData = JsonConvert.SerializeObject(replyAll);
var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
try
{
HttpResponseMessage response = httpClient.PostAsync(uriString, content).Result;
var apiResult = response.Content.ReadAsStringAsync().Result;
}
catch (Exception exception)
{
return "Error";
}
return apiResult;
}
I have a API which returns the json response.
When I call the API from Fiddler it gives me the json reponse
as shown below:
JSON Response:
Call to API from Web page:
protected void FinalCall()
{
// try
// {
string url = txtdomainURL.Text.Trim();
string apiname = txtAPIname.Text.Trim();
string apiURL = apiname+"/"+txtStoreID.Text.Trim()+"/"+txtSerialNo.Text.Trim(); //"duediligence/1/45523354232323424";// 990000552672620";//45523354232323424";
//duediligence/1/45523354232323424 HTTP/1.1
string storeID = txtStoreID.Text.Trim();//Test Store ID:1 Live Store ID: 2
string partnerID = txtPartnerID.Text.Trim();// "1";
string scretKey = txtSecretKey.Text.Trim();// "234623ger787qws3423";
string requestBody = txtRequestBody.Text.Trim(); //"{\"category\": 8}";
string data = scretKey + requestBody;
string signatureHash = SHA1HashStringForUTF8String(data);
lblSignatureHash.Text = signatureHash;
String userName = partnerID;
String passWord = signatureHash;
string credentials = userName + ":" + passWord;//Convert.ToBase64String(Encoding.ASCII.GetBytes(userName + ":" + passWord));
var dataString = JsonConvert.SerializeObject(requestBody); //JsonConvert.SerializeObject(requestBody);
var bytes = Encoding.Default.GetBytes(dataString);
WebClient client = new WebClient();
string base64 = Convert.ToBase64String(Encoding.ASCII.GetBytes(credentials));
client.Headers[HttpRequestHeader.Authorization] = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(credentials));
lblBase64.Text = base64;
client.Headers.Add(HttpRequestHeader.Accept, "application/json");
client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
//string response = cli.UploadString(url + apiURL, dataString); //"{some:\"json data\"}"
string completeURLRequest = url + apiURL;
//I GET ERROR HERE
var result = client.DownloadString(completeURLRequest);
//CODE below this line is not executed
//Context.Response.TrySkipIisCustomErrors = true;
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var jsonObject = serializer.DeserializeObject(result.ToString());
//var result1 = client.UploadData(completeURLRequest, "POST", bytes);
Response.Write(result);
txtwebresponse.Text = jsonObject.ToString();
//}
Now, When the same is executed from a web page it throws exeception '401 Unauthorized Exception'. So, instead of showing error page I want to read the returned JSON error response (as in fiddler) and show to user.
Help Appreciated!
Adapted from this answer to ".Net HttpWebRequest.GetResponse() raises exception when http status code 400 (bad request) is returned" by Jon Skeet:
try
{
using (WebResponse response = request.GetResponse())
{
Console.WriteLine("You will get error, if not do the proper processing");
}
}
catch (WebException e)
{
using (WebResponse response = e.Response)
{
HttpWebResponse httpResponse = (HttpWebResponse) response;
Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
using (Stream data = response.GetResponseStream())
using (var reader = new StreamReader(data))
{
// text is the response body
string text = reader.ReadToEnd();
}
}
}
Slightly changing SilentTremor's answer. Combining the using statements makes the code a little bit shorter.
catch (WebException ex)
{
HttpWebResponse httpResponse = (HttpWebResponse)ex.Response;
using (WebResponse response = ex.Response)
using (Stream data = response.GetResponseStream())
using (StreamReader reader = new StreamReader(data))
{
string errorMessage = reader.ReadToEnd();
}
}
I am trying to access to some rest services of a specific web server for my WP8 app and I canĀ“t do it well. For example, this is the code that I use when I try to login the user. I have to pass a string that represents a Json object ("parameters") with the username and the password and the response will be a json object too. I can't find the way to pass this pasameters in the rest request.
This is the code;
public void login(string user, string passwrd)
{
mLoginData.setUserName(user);
mLoginData.setPasswd(passwrd);
string serviceURL = mBaseURL + "/service/user/login/";
string parameters = "{\"username\":\"" + mLoginData.getUserName() + "\",\"password\":\"" + mLoginData.getPasswd() + "\"}";
//MessageBox.Show(parameters);
//MessageBox.Show(serviceURL);
//build the REST request
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serviceURL);
request.ContentType = "application/json";
request.Method = "POST";
//async request launchs "Gotresponse(...) when it has finished.
request.BeginGetResponse(new AsyncCallback(GotResponse), request);
}
private void GotResponse(IAsyncResult ar)
{
try
{
string data;
// State of request is asynchronous
HttpWebRequest myHttpWebRequest = (HttpWebRequest)ar.AsyncState;
using (HttpWebResponse response = (HttpWebResponse)myHttpWebRequest.EndGetResponse(ar))
{
// Read the response into a Stream object.
Stream responseStream = response.GetResponseStream();
using (var reader = new StreamReader(responseStream))
{
data = reader.ReadToEnd();
}
responseStream.Close();
}
}
catch (Exception e)
{
string exception = e.ToString();
throw;
}
}
I tried too with the webClient and the httpClient classes too but without any result.
Thanks and sorry for my bad english.
I solved it with the HttpClient class. This is the code.
public async void login(string user, string passwrd)
{
string serviceURL = "";
string parameters = "";
HttpClient restClient = new HttpClient();
restClient.BaseAddress = new Uri(mBaseURL);
restClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpRequestMessage req = new HttpRequestMessage(HttpMethod.Post, serviceURL);
req.Content = new StringContent(parameters, Encoding.UTF8, "application/json");
HttpResponseMessage response = null;
string responseBodyAsText = "";
try
{
response = await restClient.SendAsync(req);
response.EnsureSuccessStatusCode();
responseBodyAsText = await response.Content.ReadAsStringAsync();
}
catch (HttpRequestException e)
{
string ex = e.Message;
}
if (response.IsSuccessStatusCode==true)
{
dynamic data = JObject.Parse(responseBodyAsText);
}
else
{
if (response.StatusCode == HttpStatusCode.Unauthorized)
{
MessageBox.Show("User or password were incorrect");
}
else
{
MessageBox.Show("NNetwork connection error");
}
}
}
I wasn't setting the header values of the request correctly.
I hope this can help someone.
I am trying to post values to server authenticate method http://*/Token . From my C# client i get 400 Bad request error. While it works fine in jquery.
jQuery Code:
$( "#post2").click(function() {
var Email=$('#Email').val();
var Password=$('#Password').val();
$.ajax({
type:"Post",
url: "http://***/Token",
data:{
"grant_type": "password",
"username": Email,
"password": Password
},
success: function(msg)
{
user=msg["access_token"];
console.log(JSON.stringify(msg));
}
});
});
C# code
string email = "***#gmail.com";
string password = "***";
var tok = new TokenModel{grant_type = "password", username = email, password = password};
var s = JsonConvert.SerializeObject (tok);
var request = HttpWebRequest.Create (string.Format (#"http://***/Token", ""));
request.ContentType = "application/json";
request.Method = "POST";
using (var writer = new StreamWriter (request.GetRequestStream ())) {
writer.Write (s);
}
using (HttpWebResponse responses = request.GetResponse () as HttpWebResponse) {
}
I also tried by creating local json
var x = new
{
grant_type = "password",
username = "****#gmail.com",
password = "***"
};
But still the same error.
Is there anything i should do extra for making this call to server from C# client?
Please help,
Thanks
jQuery's ajax()'s data parameter doesn't contain a json object, but an object which later gets transformed into the post arguments (such as ?var1=foo&var2=bar).
So try:
using (WebClient client = new WebClient())
{
byte[] response = client.UploadValues("http://***/Token", new NameValueCollection()
{
{ "grant_type", "password" },
{ "username", "****#gmail.com" },
{ "password", "*****" }
});
}
Solved:
public async Task<string> Login(string username, string password)
{
HttpWebRequest request = new HttpWebRequest(new Uri(String.Format("{0}Token", "http://***.net/")));
request.Method = "POST";
string postString = String.Format("username={0}&password={1}&grant_type=password", HttpUtility.HtmlEncode(username), HttpUtility.HtmlEncode(password));
byte[] bytes = Encoding.UTF8.GetBytes(postString);
using (Stream requestStream = await request.GetRequestStreamAsync())
{
requestStream.Write(bytes, 0, bytes.Length);
}
try
{
HttpWebResponse httpResponse = (HttpWebResponse)(await request.GetResponseAsync());
string json;
using (Stream responseStream = httpResponse.GetResponseStream())
{
json = new StreamReader(responseStream).ReadToEnd();
Console.WriteLine(json);
}
TokenResponseModel tokenResponse = JsonConvert.DeserializeObject<TokenResponseModel>(json);
return tokenResponse.AccessToken;
}
catch (Exception ex)
{
Console.WriteLine ("h..........." + ex);
//throw new SecurityException("Bad ls", ex);
return null;
}
}