Httpput from an InputStreamEntity throwing 501 - httpclient

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

Related

Keycloak PUT REST 415

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?

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.

How can I marshal Objects from a Socket without closing it? (JAXB Marshaling from Inputstream via Socket)

I have tried in many different ways to send my xml document over a socket connection between a server and a client without closing the socket after sending (keep the outputstream open, for sending another document). I have found several sites who claimed that it should work, so I tried it in all the ways they sugested, but I did not found a way which works.
(that describes the same what I would like to do: http://jaxb.java.net/guide/Designing_a_client_server_protocol_in_XML.html)
The follwing code works perfectly if I am closing the socket after sending (#code marsh.marshal(element, xsw);), but it stucks on unmarshaling on the server side, if I try to keep the socket open.
Client Side....
public void sendMessage(String message){
JAXBContext jaxbContext;
try {
jaxbContext = JAXBContext.newInstance("cdl.wizard.library");
Marshaller marsh = jaxbContext.createMarshaller();
marsh.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marsh.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "http://www.example.org/WizardShema WizardsSchema.xsd");
ObjectFactory of = new ObjectFactory();
// the Dataset is the root element of the xml document
Dataset set = new Dataset("CONN01", "CONTR", "MCL01#localhost", "SV01#localhost:32000");
CommandSet cmdSet = new CommandSet();
Command cmd = new Command();
cmd.setFunctionName("RegisterAs");
Param p = new Param();
p.setString("RemoteClient");
cmd.addParameter(p);
cmdSet.addCommand(cmd);
set.setInstruction(cmdSet);
// creates a valid xml dataset, with startDocument, startElement...
JAXBElement<Dataset> element = of.createData(set);
XMLStreamWriter xsw = XMLOutputFactory.newInstance().createXMLStreamWriter(mOOS);
marsh.marshal(element, xsw);
xsw.flush();
} catch (JAXBException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (XMLStreamException e) {
e.printStackTrace();
} catch (FactoryConfigurationError e) {
e.printStackTrace();
}
SERVER Side....
private void handleMessage() {
JAXBContext jaxbContext;
try {
jaxbContext = JAXBContext.newInstance("cdl.wizard.library") ;
Unmarshaller um = jaxbContext.createUnmarshaller();
XMLInputFactory xmlif = XMLInputFactory.newInstance();
// XMLEventReader xmlr = xmlif.createXMLEventReader(mOIS);
XMLStreamReader xmlr = xmlif.createXMLStreamReader(mOIS, "UTF8");
// move to the root element and check its name.
xmlr.nextTag();
System.out.println("TagName:" + xmlr.getLocalName());
xmlr.require(START_ELEMENT, null, "Data");
JAXBElement<Dataset> obj = um.unmarshal(xmlr, Dataset.class);
Dataset set = obj.getValue();
System.out.println("ID:"+ set.getID());
} catch (JAXBException e) {
e.printStackTrace();
} catch (XMLStreamException e) {
e.printStackTrace();
} catch (FactoryConfigurationError e) {
e.printStackTrace();
}
}