Authentication failure while connecting to a URL through HTTPURLConnection - get

I wish to send sms through my java application using some third party API. While running the below code snippet with my api credentials (variable 'type' contains the url and the 'params' hold the parameters of the message like sender, receiver,message etc...), it shows Authentication failure while getting the response back. But using the same credentials in browser, it works properly and sends message. Please help me in figuring out the reason for the authentication failure.
uri = new URI( type, params , null );
URL url = uri.toURL();
HttpURLConnection conn;
conn= (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.connect();
int responseCode = conn.getResponseCode();
System.out.println(" The Response Code after Sending the SMS : "+responseCode);
InputStream isr = ((responseCode>= 200)&&(responseCode< 300)) ? conn.getInputStream() : conn.getErrorStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(isr));
String line;
StringBuilder result = new StringBuilder("");
while((line = rd.readLine()) != null)
{
result.append(line);
}
String response = result.toString();
System.out.println("The Response after Sending the SMS : "+response);

Related

HttpClient azure function returning 401 error

I have a python azure function I'm trying to integrate with a C# backend. I'm trying to upload a file from an angular front end using a c# back end to post the data.
However, I'm getting a 401 error unauthorized. My function isnt anonymous level authentication and I'm attaching the keys to the headers, but is there something I'm missing that I need to include?
I've tried adding all the authentication to the headers and the form data headers but no luck.
public HttpResponseMessage UploadPartsTemplate()
{
MultipartFormDataContent form = new MultipartFormDataContent();
Dictionary<string, string> parameters = new Dictionary<string, string>();
string baseUrl = ConfigurationManager.AppSettings["PartsProjectAPIURL"];
try
{
var fileBytes = Request.Content.ReadAsStreamAsync().Result;
client.BaseAddress = new Uri(baseUrl);
HttpContent content = new StringContent("");
content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "file",
FileName = "template.xlsx"
};
content = new StreamContent(fileBytes);
form.Add(content, "template.xlsx");
form.Headers.Add("x-functions-key", ConfigurationManager.AppSettings["XFunctionsKey"]);
form.Headers.Add("Ocp-Apim-Subscription-Key", ConfigurationManager.AppSettings["OcmAPISubscriptionKey"]);
form.Headers.Add("Ocp-Apim-Trace", "true");
form.Headers.Add("command", "validate");
form.Headers.Add("code", ConfigurationManager.AppSettings["XFunctionsKey"]);
client.DefaultRequestHeaders.Add("x-functions-key", ConfigurationManager.AppSettings["XFunctionsKey"]);
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", ConfigurationManager.AppSettings["OcmAPISubscriptionKey"]);
client.DefaultRequestHeaders.Add("Ocp-Apim-Trace", "true");
client.DefaultRequestHeaders.Add("command", "validate");
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
var response = client.PostAsync(baseUrl, form).Result;
return result;
}
catch(Exception ex)
{
throw;
}
}
And the POST Request in Postman works just fine. Any help would be appreciated!
Thank you!

Azure queue delete rest API returning "No Content" while delete API is working fine

I'm working with rest delete API. It is working fine but its returning No Content in every success response. I have given too much time but problem is still persist. Could you please correct me where I am wrong with code. I searched and implemented same but I don't know at what point I am making mistake.
public static string DeleteMessage(String queueName, string popreceipt, string messageid)
{
string requestMethod = "DELETE";
String urlPath = String.Format("{0}/messages/{1}?popreceipt={2}", queueName, Uri.EscapeDataString(messageid), Uri.EscapeDataString(popreceipt));
String storageServiceVersion = "2017-11-09";
String dateInRfc1123Format = DateTime.UtcNow.ToString("R", CultureInfo.InvariantCulture);
String canonicalizedHeaders = String.Format(
"x-ms-date:{0}\nx-ms-version:{1}",
dateInRfc1123Format,
storageServiceVersion);
//String canonicalizedResource = String.Format("/{0}/{1}", StorageAccountName, urlPath);
String canonicalizedResource = string.Format("/{0}/{1}/messages/{2}\npopreceipt:{3}", StorageAccountName, queueName, messageid, popreceipt);
String stringToSign = String.Format(
"{0}\n\n\n\n\n\n\n\n\n\n\n\n{1}\n{2}",
requestMethod,
canonicalizedHeaders,
canonicalizedResource);
String authorizationHeader = CreateAuthorizationHeader(stringToSign);
Uri uri = new Uri("https://" + StorageAccountName + ".queue.azure.com/" + urlPath);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = requestMethod;
request.Headers.Add("x-ms-date", dateInRfc1123Format);
request.Headers.Add("x-ms-version", storageServiceVersion);
request.Headers.Add("Authorization", authorizationHeader);
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
Stream dataStream = response.GetResponseStream();
return response.StatusCode.ToString();
}
}
public static String CreateAuthorizationHeader(String canonicalizedString)
{
String signature = String.Empty;
using (HMACSHA256 hmacSha256 = new HMACSHA256(Convert.FromBase64String(StorageAccountKey)))
{
Byte[] dataToHmac = System.Text.Encoding.UTF8.GetBytes(canonicalizedString);
signature = Convert.ToBase64String(hmacSha256.ComputeHash(dataToHmac));
}
String authorizationHeader = String.Format(
CultureInfo.InvariantCulture,
"{0} {1}:{2}",
"SharedKey",
StorageAccountName,
signature
);
return authorizationHeader;
}
This is expected behavior. Delete Message operation is supposed to return no content. From the documentation here:
Status code
A successful operation returns status code 204 (No
Content).
As an addition to Gaurav's answer: deleting a message is not the same as getting or dequeuing a message. What would you expect calling DELETE to return?
According to MDN (DELETE - responses):
If a DELETE method is successfully applied, there are several response status codes possible:
A 202 (Accepted) status code if the action will likely succeed but has not yet been enacted.
A 204 (No Content) status code if the action has been enacted and no further information is to be supplied.
A 200 (OK) status code if the action has been enacted and the response message includes a representation describing the status.

Trigger notification after Computer Vision OCR extraction is complete

I am exploring Microsoft Computer Vision's Read API (asyncBatchAnalyze) for extracting text from images. I found some sample code on Microsoft site to extract text from images asynchronously.It works in following way:
1) Submit image to asyncBatchAnalyze API.
2) This API accepts the request and returns a URI.
3) We need to poll this URI to get the extracted data.
Is there any way in which we can trigger some notification (like publishing an notification in AWS SQS or similar service) when asyncBatchAnalyze is done with image analysis?
public class MicrosoftOCRAsyncReadText {
private static final String SUBSCRIPTION_KEY = “key”;
private static final String ENDPOINT = "https://computervision.cognitiveservices.azure.com";
private static final String URI_BASE = ENDPOINT + "/vision/v2.1/read/core/asyncBatchAnalyze";
public static void main(String[] args) {
CloseableHttpClient httpTextClient = HttpClientBuilder.create().build();
CloseableHttpClient httpResultClient = HttpClientBuilder.create().build();;
try {
URIBuilder builder = new URIBuilder(URI_BASE);
URI uri = builder.build();
HttpPost request = new HttpPost(uri);
request.setHeader("Content-Type", "application/octet-stream");
request.setHeader("Ocp-Apim-Subscription-Key", SUBSCRIPTION_KEY);
String image = "/Users/xxxxx/Documents/img1.jpg";
File file = new File(image);
FileEntity reqEntity = new FileEntity(file);
request.setEntity(reqEntity);
HttpResponse response = httpTextClient.execute(request);
if (response.getStatusLine().getStatusCode() != 202) {
HttpEntity entity = response.getEntity();
String jsonString = EntityUtils.toString(entity);
JSONObject json = new JSONObject(jsonString);
System.out.println("Error:\n");
System.out.println(json.toString(2));
return;
}
String operationLocation = null;
Header[] responseHeaders = response.getAllHeaders();
for (Header header : responseHeaders) {
if (header.getName().equals("Operation-Location")) {
operationLocation = header.getValue();
break;
}
}
if (operationLocation == null) {
System.out.println("\nError retrieving Operation-Location.\nExiting.");
System.exit(1);
}
/* Wait for asyncBatchAnalyze to complete. In place of this wait, can we trigger any notification from Computer Vision when the extract text operation is complete?
*/
Thread.sleep(5000);
// Call the second REST API method and get the response.
HttpGet resultRequest = new HttpGet(operationLocation);
resultRequest.setHeader("Ocp-Apim-Subscription-Key", SUBSCRIPTION_KEY);
HttpResponse resultResponse = httpResultClient.execute(resultRequest);
HttpEntity responseEntity = resultResponse.getEntity();
if (responseEntity != null) {
String jsonString = EntityUtils.toString(responseEntity);
JSONObject json = new JSONObject(jsonString);
System.out.println(json.toString(2));
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
There is no notification / webhook mechanism on those asynchronous operations.
The only thing that I can see right know is to change the implementation you mentioned by using a while condition which is checking regularly if the result is there or not (and a mechanism to cancel waiting - based on maximum waiting time or number of retries).
See sample in Microsoft docs here, especially this part:
// If the first REST API method completes successfully, the second
// REST API method retrieves the text written in the image.
//
// Note: The response may not be immediately available. Text
// recognition is an asynchronous operation that can take a variable
// amount of time depending on the length of the text.
// You may need to wait or retry this operation.
//
// This example checks once per second for ten seconds.
string contentString;
int i = 0;
do
{
System.Threading.Thread.Sleep(1000);
response = await client.GetAsync(operationLocation);
contentString = await response.Content.ReadAsStringAsync();
++i;
}
while (i < 10 && contentString.IndexOf("\"status\":\"Succeeded\"") == -1);
if (i == 10 && contentString.IndexOf("\"status\":\"Succeeded\"") == -1)
{
Console.WriteLine("\nTimeout error.\n");
return;
}
// Display the JSON response.
Console.WriteLine("\nResponse:\n\n{0}\n",
JToken.Parse(contentString).ToString());

failure sending HTTP GET request using httpconnection

I am stuck getting a failure back from my request. This works in postman but when trying in java, it fails every way I try it. Sample code below along with the response I get. I am able to send an HTTPPost to this webservice successfully using httpsurlconnection and outputstreamwriter but when trying to convert this to a GET without any that are not in the URL itself, it fails. Any help is very appreciated!!
//print out the encoded values
data.addToLog( “sha256hex: “, sha256hex);
data.addToLog( “xauth: “, xauth);
StringBuilder sb = new StringBuilder();
String baseurl = “https://” + apihost + endpoint + “?personID=” + personid;
data.addToLog( “BaseURL: “, baseurl);
//print out the JSON search request
try {
URL myurl = new URL(null, baseurl , new sun.net.www.protocol.https.Handler() );
HttpsURLConnection con = (HttpsURLConnection )myurl.openConnection();
con.setSSLSocketFactory(new TSLSocketConnectionFactory());
con.setRequestProperty(“X-Timestamp”, tsparam);
con.setRequestProperty(“X-Nonce”, nonce64);
con.setRequestProperty(“X-Authorization”, xauth);
con.setRequestProperty(“X-Test-Insecure”, “true”);
con.setRequestMethod(method);
con.setDoOutput(true);
con.setRequestProperty(“Content-Type”, “application/json;charset=utf-8”);
int responseCode = con.getResponseCode();
data.addToLog(“Response Code= “, con.getResponseCode() +”: “+ con.getResponseMessage());
if (responseCode == HttpURLConnection.HTTP_OK) { // success
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
//System.out.println(response.toString());
data.addToLog(“Response:”, response.toString() );
}
Log results:
PersonDetailsLookup,custom,Response Code= ,200: OK
PersonDetailsLookup,custom,Response:,{“serviceModel”:{“errorCode”:{“description”:”Unexpected System Error””value”:”500″}”errorMessage”:”API Invocation Failure – Unknown Error””severity”:{“description”:”FATAL””value”:”3″}}}
Figured it out! It was the content type and it needed to be changed to text instead of json:
con.setRequestProperty(“Content-Type”, “application/text;charset=utf-8”);

groovy HTTP Builder not returning results

I have the following code in groovy
HTTPBuilder http = new HTTPBuilder("https://ronna-afghan.harmonieweb.org/_layouts/searchrss.aspx")
http.request(Method.GET, groovyx.net.http.ContentType.XML) {
// set username and password for basic authentication
// set username and password for basic auth
//http.auth.basic(ConfigurationHolder.config.passportService.userName,
// ConfigurationHolder.config.passportService.password)
headers.'User-Agent' = 'Mozilla/5.0'
uri.query = [k:'execution']
// response handler for a success response code:
response.success = {resp, xml ->
println resp.statusLine
log.debug "response status: ${resp.statusLine}"
log.debug xml.toString()
}
// handler for any failure status code:
response.failure = {resp ->
log.error " ${resp.statusLine.statusCode} : ${resp.statusLine.reasonPhrase}"
}
}
when I run the code, it doesn't give me the rss feed which I'm suppose to get
When I have the same code in java
try {
// Create a URLConnection object for a URL
URL oracle = new URL(
"https://ronna-afghan.harmonieweb.org/_layouts/srchrss.aspx?k=execution&count=1&format=rss");
URLConnection yc = oracle.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
in.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
it returns the xml Rss. I can't figure what the issue might be. Everything looks okay to me in the groovy code and also the Http return code is 200.
The code that you have described in Java is the equivalent of the following code in Groovy:
def oracle = "https://ronna-afghan.harmonieweb.org/_layouts/srchrss.aspx?k=execution&count=1&format=rss".toURL().text

Resources