I tried setting the Accept header as application/json and during service invocation i could see "DEBUG o.s.web.client.RestTemplate - Setting request Accept header to [text/plain, /]" written in logs. Is my accept header overwritten ? how to restrict?
Code snippet:
RestTemplate template = new RestTemplate();
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.add(HttpHeaders.CONTENT_TYPE, APPLICATION_JSON);
requestHeaders.add(HttpHeaders.ACCEPT, APPLICATION_JSON);
String url = "http://*******"
HttpEntity<String> request = new HttpEntity<String>(requestBody, requestHeaders);
HttpEntity<String> response = template.exchange(url, HttpMethod.POST, request, String.class);
Logs:
{Content-Type=[application/json], Accept=[application/json]}
13:08:06.091 [main] DEBUG o.s.web.client.RestTemplate - Created POST request for "http://********"
13:08:06.097 [main] DEBUG o.s.web.client.RestTemplate - Setting request Accept header to [text/plain, */*]
Related
I want to send to webdav server a 100 files in one request. I'm getting list of messages, then I creating binary body parts of them. This is my code which gets me 301 http error response code. When I send one file it's working but expected behaviour is to send parts of files. And I want it to be created one file by one on the server, is it possible?
CloseableHttpClient client = HttpClients.createDefault();
HttpPut httpPost = new HttpPut("http://localhost:8888/webdav"); // I also tried with / at the end
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
messages.forEach(m -> {
builder.addBinaryBody("file", new File(Paths.get(m.getPath()).toAbsolutePath().toString()),
ContentType.APPLICATION_OCTET_STREAM, m.getFileName() + ".encryptedByAes");
builder.addBinaryBody("file", new File(Paths.get(m.getAesPath()).toAbsolutePath().toString()),
ContentType.APPLICATION_OCTET_STREAM, m.getFileName() + ".aes");
});
HttpEntity multipart = builder.build();
httpPost.setEntity(multipart);
UsernamePasswordCredentials creds
= new UsernamePasswordCredentials("test", "test");
httpPost.addHeader(new BasicScheme().authenticate(creds, httpPost, null));
CloseableHttpResponse response = client.execute(httpPost);
if (response.getStatusLine().getStatusCode() != HTTP_OK) {
throw new WebDavException("Error while executing request to webdav server with messages");
}
client.close();
I want to consume html response using restTemplate and rerun that response to my html so i can add those content to my html page but getting below error tried so many alternatives but not luck
I want to consume every type of response and return that as it is to my html/jsp via ajax and render that content in a div.
HTML (ajax call) --- Spring MVC (rest call to 3rd party) --- application returns html
Code
#RequestMapping(value = "/xyz-service/**", method = {RequestMethod.GET, RequestMethod.PUT},produces="application/json;charset=UTF-8")
public Object mirrorRest(HttpServletRequest request) {
String url = request.getRequestURI();
return restTemplate.getForObject("http://xyz-service:8080"+url , String.class);
}
I am able to invoke my serive method that retuning html as respose but getting error
"Could not extract response: no suitable HttpMessageConverter found for response type [class java.lang.String] and content type [text/html;charset=UTF-8]"
]
The exception seem to have occurred because your request was missing the header parameters.
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", "Bearer " + apikey);
headers.set("Charset", "utf-8");
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<Request> entity = new HttpEntity<Request>(
req, headers); //incase if your request have a request body
try {
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class); //if no request body you could simply use headers parameter directly
logger.info(response.toString());
return response.getBody().toString();
} catch (HttpStatusCodeException exception) {
logger.info("API failed"+exception);
return null;
}
No you can't. An HTML page is not a json object: REST template is designed to consume RestServices.
You should use a URLConnection from jdk
I am using HttpGet with a proxy setting. The call works for endpoints that don't need an authorization token. For services that need a token, I use setHeader(), but see an error saying auth token missing.
What am I missing ?
HttpGet get = new HttpGet(endPoint);
get.setHeader("Authorization", token);
HttpHost proxy = new HttpHost("exampleproxy.com",8080);
RequestConfig config = RequestConfig.custom() .setProxy(proxy).build();
get.setConfig(config);
CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
CloseableHttpResponse response = httpclient.execute(get);
BufferedReader responseReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
Hi I am trying to get the list of graphs in MarkLogic using RestTemplate.
Below is the sample code. From the browser I can able to get the graph list, but through the Java REST Client I am getting error 401.
HttpHeaders header = new HttpHeaders();
String plainCreds = "restadmin:restpassword";
byte[] plainCredsBytes = plainCreds.getBytes();
byte[] base64CredsBytes = Base64.encode(plainCredsBytes);
String base64Creds = new String(base64CredsBytes);
header.setAccessControlAllowCredentials(true);
header.add("Authorization", "Basic " + base64Creds);
header.setAccept(Arrays.asList(MediaType.TEXT_XML));
header.setContentType(MediaType.TEXT_XML);
HttpEntity<String> entity = new HttpEntity<String>(header);
String url = "http://localhost:8003/v1/graphs";
ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
System.out.println("Response : "+response.getStatusCode());
Please help me in resolving the issue
Try copying the HTTP auth code at https://github.com/rjrudin/ml-app-deployer/blob/master/src/main/java/com/rjrudin/marklogic/rest/util/RestTemplateUtil.java#L18 - I know it will handle HTTP basic auth against the management API on port 8002, and it should work fine on your REST API server on port 8003.
I am trying to hit .svc service from my JME application using POST method. but getting 'bad request'. Following is my code.
HttpConnection hc = (HttpConnection) Connector.open(url, Connector.READ_WRITE);
hc.setRequestMethod(HttpConnection.POST);
hc.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Configuration/CLDC-1.0" );
hc.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
hc.setRequestProperty("Content-Length", ""+(postMsg.getBytes().length));
out = hc.openOutputStream();
out.write(postMsg.getBytes());
System.out.println("hc.getResponseCode() = "+hc.getResponseCode()+ " hc.getResponseMessage() = "+hc.getResponseMessage());
Please tell me what is wrong with the code.
Instead of http, I used Ksoap2-j2me-core jar with following code that i found -
SoapObject request = new SoapObject("namespace", "login");
request.addProperty("username", "pranav");
request.addProperty("password", "gangan");
//create the SOAP envelope
final SoapSerializationEnvelope env = new SoapSerializationEnvelope(SoapEnvelope.VER11);
env.setOutputSoapObject(request);
//create the transport and then call
final HttpTransport httpTransport = new HttpTransport("http://URL");
httpTransport.call("\"login\"", env);
SoapObject body = (SoapObject) env.bodyIn;
//body.getProperty(0) will return the content of the first tag inside body
Object response = body.getProperty(0);
System.out.println(response.toString);