I have a spring boot service calling another spring boot service.
Both services deployed into docker container.
And when the first service calling the second service, the second service got 401 response. While when i do the same request using PostMan I got a valid response.
Given I am using the credential through postman and the service itself.
Any Idea why this may happen? Is there any related to docker deployment ?
Code used to call the second service
try {
urlStr = licenseRequest.getString(LicenseRequest.URL);
logger.info("URL: "+ urlStr);
URL url = new URL(urlStr);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("Content-Type", "application/json");
// auth
String authStrEncoded = Base64Utils.encodeToString((username + ":" + password).getBytes());
con.setRequestProperty("Authorization", "Basic " + authStrEncoded);
if (!licenseRequest.isNull(LicenseRequest.BODY))
{
String body = licenseRequest.getString(LicenseRequest.BODY);
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream (
con.getOutputStream());
wr.write(body.getBytes());
wr.close();
}
//Get Response
InputStream is = con.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
StringBuilder response = new StringBuilder(); // or StringBuffer if Java version 5+
String line;
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
return response.toString();
}
Related
Uploading an object from a .net webclient to MinIO where the object contains special characters in the name issues an HTTP 403.
This object fails: old_me_bold+19(1).jpg
This object is ok: old_me_bold19.jpg
The message is:
The request signature we calculated does not match the signature you provided. Check your key and signing method.
What is breaking in MinIO?
Encoding the Url did not work either. I also tried PresignedPutObjectAsync to create a tmp Url already signed then I did a PUT using an HttpClient with the same result. To test that this way would work, I removed the special characters from the name of the file and the client was able to send the file to MinIO.
This code fails:
public async System.Threading.Tasks.Task PutAttachementAsync(
Attachment attachment,
string bukectName,
string objectName,
string attachmentType = "application/octet-stream")
{
using (HttpClient client = new HttpClient())
{
var minioClient = GetMinioClient();
client.BaseAddress = new Uri(Config.Instance.GetConfig("MinIOURL"));
var tempFileName = CreateAttachmentTempFile(attachment, out bool virusScanResult);
if (!virusScanResult)
return;
using (FileStream str = new FileStream(tempFileName.FileAttachmentPath, FileMode.Open))
{
try
{
String signedTMPUrl = await minioClient.PresignedPutObjectAsync(bukectName, objectName, 60 * 60 * 24);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(attachmentType));
HttpResponseMessage response = await client.PutAsync(signedTMPUrl, new StreamContent(str));
if (response.IsSuccessStatusCode)
{
Log.InfoFormat("Request Message Information:- \n\n" + response.RequestMessage + "\n");
Log.InfoFormat("Response Message Header \n\n" + response.Content.Headers + "\n");
}
else
{
Log.InfoFormat("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
}
}
catch (MinioException e)
{
Log.Error("Error occurred: " + e.Message);
}
}
}
}
That code is running from an ASP.Net application hosted in IIS. I wonder if IIS is injecting something into the header before the message goes to MinIO.
Any other file that I send to MinIO, if the name does not contain characters such as (), then the upload works always.
I' getting following error when I try to run the application in the server. Some of APIs working in the server without an issue and only one API giving following error.
javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated
at sun.security.ssl.SSLSessionImpl.getPeerCertificates(SSLSessionImpl.java:397)
at org.apache.http.conn.ssl.AbstractVerifier.verify(AbstractVerifier.java:128)
at org.apache.http.conn.ssl.SSLSocketFactory.connectSocket(SSLSocketFactory.java:390)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:148)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:149)
This is the code I'm trying to access the API.
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(
"https://mife.smobile.lk/apicall/dialogloanprepaid/v1.0/auto");
JSONObject json = new JSONObject();
StringEntity params = new StringEntity("{\"msisdn\":\"" + mobile
+ "\",\"channel\":\"IVR\"}");
new StringEntity(json.toString());
post.addHeader("content-type", "application/json");
post.addHeader("Authorization", "Bearer " + access_token);
post.addHeader("Accept", "application/json");
post.setEntity(params);
HttpResponse response = client.execute(post);
int status = response.getStatusLine().getStatusCode();
System.out.println("status code is :" + status);
resCode = Integer.toString(status);
BufferedReader rd = new BufferedReader(new InputStreamReader(
response.getEntity().getContent()));
String response1 = readAll(rd);
System.out.println(response1);
JSONObject obj = new JSONObject(response1);
resCode = obj.getString("resCode");
resDesc = obj.getString("resDesc");
Is there anything can be done from the code level in order to sort out the issue. Please help.
I'm using the HttpURLConnection POST to get the response. Im able to get the responsecode 200 but the responseString is getting encoded as below::
���������RP�b��%+c//17�Wr
��u���v����QJ�r��-�N�9���
here is the code I'm using::
public static String getPOSTAJAX(String getURL,String impersonationID,String getPOSTParameters)
{
// get Impersonation ID
String getimpersonationID = "bearer "+impersonationID;
String getResponseline = "";
String getPOSTResponse = null;
String postCookies = "sid="+impersonationID;
try
{
//Open HttpURLConnection
URL url = new URL(getURL);
HttpURLConnection urlConn = (HttpURLConnection)url.openConnection();
//add request header
if (impersonationID != null && impersonationID != " ") {
urlConn.setRequestProperty("Authorization", getimpersonationID);
urlConn.setRequestProperty("Accept-Encoding","gzip, deflate");
urlConn.setRequestProperty("Cookie", postCookies);
}
urlConn.setRequestProperty("Accept","application/json,text/plain,*/*");
urlConn.setRequestProperty("Accept-Language", "en-US,en;q=0.8");
urlConn.setRequestProperty("Connection", "keep-alive");
urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
urlConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.94 Safari/537.36");
urlConn.setRequestMethod("POST");
urlConn.setRequestProperty("Content-Length", String.valueOf(getPOSTParameters.getBytes().length));
urlConn.setRequestProperty("X-Requested-With", "XMLHttpRequest");
//send the POSt Request
urlConn.setDoOutput(true);
urlConn.setDoInput(true);
DataOutputStream writeRequest = new DataOutputStream(urlConn.getOutputStream());
writeRequest.writeBytes(getPOSTParameters);
writeRequest.flush();
writeRequest.close();
//To get the Response Codes
int responseCode = urlConn.getResponseCode();
logger.debug("\nSending 'POST' request to URL::" +url);
logger.debug("Post parameters ::"+getPOSTParameters);
logger.debug("Response Code ::" + responseCode);
//parse the response
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream(), Charset.forName("UTF-8")));
while((getResponseline = reader.readLine()) != null)
{
builder.append(getResponseline);
builder.append("\n");
}
reader.close();
getPOSTResponse = builder.toString();
//logger.debug("\n "+getPOSTResponse);
//Disconnect the connection
urlConn.disconnect();
}
catch (IOException ioe) {
logger.error("\n"+ioe);
}
return getPOSTResponse;
}
can anyone suggest how to decode the response?
Instead of using InputStreamReader,I would suggest to use InflaterInputStream class,which can be used to uncompress data.
StringBuilder builder = new StringBuilder();
InflaterInputStream in = new InflaterInputStream(urlConn.getInputStream()), new Inflater(true));
int i;
while((i=in.read())!=-1){
builder.append(i);
}
getPOSTResponse = builder.toString();
I 've had the same problem too and I removed all request properties except Content-Type, and now it is working.
Donno how/why it works now.
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;
}