failure sending HTTP GET request using httpconnection - get

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”);

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.

Unable to parse some UTF-8 characters in a txt file uploaded from Spring POST Method

I have been trying to make a string validator but some characters in the input have some swedish characters which I haven't been able to parse. I have been going mad about this. Tried everything I found on the internet. Can anybody please help me out?
This is the logic for reading the file. I have been trying to parse it.
I haven't been able to specifically parse this word: leverantör. It's parsed as leverant�r.
public String processFile(MultipartFile file) throws IOException, FormatNotFoundException {
// TODO Auto-generated method stub
BufferedReader r = new BufferedReader(new InputStreamReader(file.getInputStream()));
String output;
while((output = r.readLine())!=null ) {
logger.debug(output);
InputStream is= new ByteArrayInputStream(output.getBytes(StandardCharsets.UTF_8));
StringBuilder textBuilder = new StringBuilder();
try (
Reader reader = new BufferedReader(new InputStreamReader
(is, Charset.forName(StandardCharsets.UTF_8.name())))) {
int c = 0;
while ((c = reader.read()) != -1) {
textBuilder.append((char) c);
}
}
logger.debug(textBuilder.toString());
System.out.println(textBuilder.toString());
}
return "File read.";
}

Authentication failure while connecting to a URL through HTTPURLConnection

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

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