Keycloak PUT REST 415 - rest

I am getting the following error message when trying to CALL REST API of Keycloak used HttpClient.The code as following:
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = servletRequestAttributes.getRequest();
String token = request.getHeader("X-Auth-Token");
String url = authUrl + "/admin/realms/fast/users/"+userId+"/reset-password";
CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
HttpPut httpPut = new HttpPut(url);
httpPut.addHeader("Authorization", token);
httpPut.addHeader("Content-Type ", "application/json");
List<NameValuePair>list = new ArrayList<NameValuePair>();
list.add(new BasicNameValuePair("type", "password"));
list.add(new BasicNameValuePair("value",userPassDO.getNewPassword()));
list.add(new BasicNameValuePair("temporary","true"));
UrlEncodedFormEntity entity;
try {
entity = new UrlEncodedFormEntity(list,"UTF-8");
httpPut.setEntity(entity);
CloseableHttpResponse response = closeableHttpClient.execute(httpPut);
HttpEntity et = response.getEntity();
InputStream in = et.getContent();
int stat= response.getStatusLine().getStatusCode();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The response after execute put request show an error
"HttpResponseProxy{HTTP/1.1 415 Unsupported Media Type [Server: nginx/1.15.3, Date: Tue, 30 Oct 2018 09:13:03 GMT, Content-Length: 0, Connection: keep-alive] [Content-Length: 0,Chunked: false]"
Does anyone have any ideas or encountered this problem?

Related

Httpput from an InputStreamEntity throwing 501

I am reading from Object Storage and making a httpPut call to another target URL, but this call fails with 501 Method Not Implemented. Not sure what I am doing wrong.
import com.oracle.bmc.objectstorage.responses.GetObjectResponse;
...
...
GetObjectResponse getResponse =
client.getObject(
GetObjectRequest.builder()
.namespaceName(namespaceName)
.bucketName(bucketName)
.objectName(objectName)
.build());
try (final InputStream fileStream = getResponse.getInputStream()) {
InputStreamEntity entity = new InputStreamEntity(fileStream, -1);
entity.setContentType("text/html; charset=utf-8");
HttpPut putRequest = new HttpPut("https://MYURL");
putRequest.setEntity(entity);
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpResponse response= httpClient.execute(putRequest);
if (response != null) {
// FOR DEBUGGING System.out.println(response.getStatusLine().getStatusCode());
}
}
catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}}

Spring boot return application/pdf with a ResponseEntity<Resource>

In my springboot application, I try to return a pdf file with a ResponseEntity-Resource- to mock a service. So I can't change the return type of this method.
My code :
#RequestMapping(
value = "/pdf",
produces = MediaType.APPLICATION_PDF_VALUE,
method = RequestMethod.GET
)
public ResponseEntity<Resource> getpdf() {
try {
ClassPathResource pdfFile = new ClassPathResource("sample.pdf");
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_METHODS, "GET, POST, PUT");
headers.add(HttpHeaders.ACCESS_CONTROL_ALLOW_HEADERS, "Content-Type");
headers.add(HttpHeaders.CACHE_CONTROL, "no-cache, no-store, must-revalidate");
headers.add(HttpHeaders.PRAGMA, "no-cache");
headers.add(HttpHeaders.EXPIRES, "0");
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + pdfFile.getFilename());
headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_PDF_VALUE);
log.info("pdfFile.contentLength() : " + pdfFile.contentLength());
return ResponseEntity
.ok()
.headers(headers)
//.contentLength(pdfFile.contentLength())
//.contentType(MediaType.APPLICATION_PDF)
.body(new InputStreamResource(pdfFile.getInputStream()));
} catch (IOException e) {
log.error("Couldn't serialize response for content type ", e);
return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
When I try to call this get with postman or swagger I have a 406 with response header :
{
"date": "Fri, 02 Nov 2018 14:04:44 GMT",
"content-length": "0",
"content-type": null
}
Does anyone have an idea?
Swagger response
way too complex.. downloading a file is much more easy
#GetMapping(value="printing/",produces= MediaType.APPLICATION_PDF_VALUE)
public #ResponseBody byte[] print(#RequestParam("filterParam") String filterParam) {
try {
FileInputStream fis= new FileInputStream(new File("path to your file"));
byte[] targetArray = new byte[fis.available()];
fis.read(targetArray);
return targetArray;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
You can remove produces = MediaType.APPLICATION_PDF_VALUE.
There is no need to add produces = MediaType.APPLICATION_PDF_VALUE, in RequestMapping as it seems to try to convert the ResponeBody internally.
Below line of code is enough which you are already using.
headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_PDF_VALUE);

Android:Restful webservice put method showing response with status 405 Method not allowed

I am getting data by http get through restful webservice hosted on IIS7 but when i am trying to put data i am having problem
MY code for put is as follows:
public Void put(String url, List<NameValuePair> data)
{
String response="";
HttpPut put = new HttpPut(url);
String dataString=data.toString();
HttpClient httpclient = new DefaultHttpClient();
try {
StringEntity entity = new StringEntity(dataString, "UTF-8");
entity.setContentType("x-www-form-urlencoded; charset=UTF-8");
put.setEntity(entity);
HttpResponse httpResponse1 = httpclient.execute(put);
StatusLine statusLine = httpResponse1.getStatusLine();
}catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
httpclient.getConnectionManager().shutdown();
}
}
The response i am getting is 405 Method not allowed, Can anybody tell me what is the problem?
You just have to uncheck webdave feature from the IIS menu which is in the window's features

Applet: SocketException Unknown proxy type : HTTP

I have no problems running my applet in Eclipse, but if I sign and run it in browser this happend
10-abr-2013 19:54:37 org.apache.http.impl.client.DefaultHttpClient tryConnect
INFO: I/O exception (java.net.SocketException) caught when connecting to the target host: Unknown proxy type : HTTP
10-abr-2013 19:54:37 org.apache.http.impl.client.DefaultHttpClient tryConnect
INFO: Retrying connect
…
java.net.SocketException: Unknown proxy type : HTTP
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
Here im trying to upload some files using org.apache.http.client.HttpClient
public static String executeMultiPartRequest(String urlString, File file,
String fileName, String fileDescription) {
System.out.println("SET URI " + urlString);
HttpPost postRequest = new HttpPost(urlString);
try {
MultipartEntity multiPartEntity = new MultipartEntity();
// The usual form parameters can be added this way
multiPartEntity.addPart("fileDescription", new StringBody(
fileDescription != null ? fileDescription : ""));
multiPartEntity.addPart("fileName", new StringBody(
fileName != null ? fileName : file.getName()));
/*
* Need to construct a FileBody with the file that needs to be
* attached and specify the mime type of the file. Add the fileBody
* to the request as an another part. This part will be considered
* as file part and the rest of them as usual form-data parts
*/
FileBody fileBody = new FileBody(file, "application/octect-stream");
multiPartEntity.addPart("attachment", fileBody);
// multiPartEntity.addPart("path", Charset.forName("UTF-8"));
postRequest.setEntity(multiPartEntity);
} catch (UnsupportedEncodingException ex) {
ex.printStackTrace();
}
return executeRequest(postRequest);
}
private static String executeRequest(HttpRequestBase requestBase) {
String responseString = "";
InputStream responseStream = null;
HttpClient client = new DefaultHttpClient();
try {
System.out.println("LISTO PARA ENVIAR A" + requestBase.getURI());
HttpResponse response = client.execute(requestBase);
if (response != null) {
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
responseStream = responseEntity.getContent();
if (responseStream != null) {
BufferedReader br = new BufferedReader(
new InputStreamReader(responseStream));
String responseLine = br.readLine();
String tempResponseString = "";
while (responseLine != null) {
tempResponseString = tempResponseString
+ responseLine
+ System.getProperty("line.separator");
responseLine = br.readLine();
}
br.close();
if (tempResponseString.length() > 0) {
responseString = tempResponseString;
}
}
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (responseStream != null) {
try {
responseStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
client.getConnectionManager().shutdown();
return responseString;
}
What its wrong?
Applet is signed and compiled with java 1.6, httpclient-4.1.3.jar
For those with this problem, the solution was here http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d5e571 getting the JRE Proxy.
DefaultHttpClient client = new DefaultHttpClient () ;
ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(
client.getConnectionManager().getSchemeRegistry(),
ProxySelector.getDefault());
client.setRoutePlanner(routePlanner);
HttpResponse response = client.execute(requestBase) ;
Then i signed all libraries httpcore-4.2.3.jar, httpmime-4.2.3.jar and httpclient-4.2.3.jar.

POST over SSL/HTTPS REST Api Android is responding 400 Bad Request

In my application I want to post from my android application XML data in the remote server which is using REST service. My code is below:
String url = "api.example.com";
int port = 443;
String query = "<?xml version='1.0' encoding='UTF-8'?><request><client><name>APIappDevAccount</name><password>123456</password></client><user><name>foyzulkarim</name><password>123456</password><groupId>12345</groupId></user></request>";
Socket socket = null;
try {
socket = new Socket(url,port);
} catch (UnknownHostException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
PrintStream pw = null;
try {
pw = new PrintStream(socket.getOutputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pw.print("POST api.example.com/rest/rest/user");
pw.print("Content-Type: application/xml");
pw.print("Content-Length:" + query.length());
pw.print(query);
System.out.println("hello foysal.");
//get result
String l = null;
String text="";
try {
while ((l=br.readLine())!=null) {
System.out.println(l);
text+=l;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
pw.close();
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
But that server is behind SSL/HTTPS protocol so i am getting the below 400 Bad Request as response.
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"><html><head><title>400 Bad Request</title></head><body><h1>Bad Request</h1><p>Your browser sent a request that this server could not understand.<br />Reason: You're speaking plain HTTP to an SSL-enabled server port.<br />Instead use the HTTPS scheme to access this URL, please.<br /><blockquote>Hint: <b>https://api.example.com/</b></blockquote></p></body></html>
If I use SSLSocketFactory like below
SocketFactory socketFactory = SSLSocketFactory.getDefault();
Socket socket = null;
try {
socket = socketFactory.createSocket(url, port);
I got exception
javax.net.ssl.SSLException: Not trusted server certificate
java.security.cert.CertPathValidatorException: TrustAnchor for CertPath not found.
at line
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
My question is, how can i post the data over SSL from android application in my above scenario?
I guess many of us are facing this problem, so I am requesting you to give me/us some elaborated answers.Cheers.
Too many unknowns :-)
Try plain HTTP against a test server you have control over.
My hunch is it will give the same error.
You don't seem to put an empty line between the HTTP headers and body for example.
Why are you re-implementing HTTP anyway? Don't tell me there's no API or library you could use on whatever platform this is? Usually there's java.net.HttpUrlConnection, or Apache HttpClient.
Edit:
Hey, look what google brought in: http://developer.android.com/reference/android/net/http/AndroidHttpClient.html
It seems that I needed to add the TrustAnchor certificate to be able to validate the whole key chain.
I have requested about this certificate to my API Provider and they given me the web link from where I can get the certificate. [i have changed the web link for confidentiality]
https://www.example.com/library/......SSL_bundle.pem
They also told me to get try the connection via (i guess it should be executed from command prompt)
openssl s_client -connect api.example.com:443 -CAfile /root/SSL_bundle.pem
I then have to integrate the certificate into my application.
I will now try to know how can I integrate that certificate, but that discussion should be in another question.
I have done it. The code is given below.
private String executeRequest(String targetURL, final String requestMethod,
String soap_request_message_header, String soap_request_message_body) {
URL url;
HttpURLConnection connection = null;
try {
url = new URL(targetURL);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(requestMethod);
connection.setRequestProperty("SOAPAction",
soap_request_message_header);
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
// Send request
DataOutputStream wr = new DataOutputStream(connection
.getOutputStream());
wr.writeBytes(soap_request_message_body);
wr.flush();
wr.close();
// Get Response
InputStream is;
final int responseCode = connection.getResponseCode();
Log.i("response", "code=" + responseCode);
if (responseCode <= 400) {
is = connection.getInputStream();
} else {
/* error from server */
is = connection.getErrorStream();
}
// is= connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
Log.i("response", "" + response.toString());
return response.toString();
} catch (Exception e) {
Log.e("error https", "", e);
return e.getMessage();
} finally {
if (connection != null) {
connection.disconnect();
}
}
}