i am trying to access gaana api from java side by using mashape api
i am trying from a localhost. but, i am getting issues while trying to connect gaana api.
Below is my code in one of my rest service ( I am using spring-security and java8). I am Btech-CSE final year student.
#RestController
#RequestMapping("/api/ideas")
public class IdeaController {
#RequestMapping(method = RequestMethod.GET)
public void invokeGaanaAPI() throws UnirestException {
System.out.println("hello");
// These code snippets use an open-source library.
// HttpServletResponse<JsonNode> response =
Unirest.get("https://community-gaana.p.mashape.com/index.php?subtype=most_popular&type=song")
.header("X-Mashape-Key", "iWEvla5JyCmshafdpHdjoSdtPsHPp1Ily4qjsnCEiVxbQsY5tn")
.header("Accept", "application/json")
.asJson();
Unirest.get("https://community-gaana.p.mashape.com/user.php?type=registrationtoken")
.header("X-Mashape-Key", "iWEvla5JyCmshafdpHdjoSdtPsHPp1Ily4qjsnCEiVxbQsY5tn")
.header("Accept", "application/json")
.asJson();
System.out.println("hello");
}
}
I need help to proceed in this situation. any kind of help is fine for me. i am getting data as null. so, json conversion is throwing null pointer exception.
I am passionate to do this project.
Your data is null because you haven't assigned the Unirest.get() return value to anything.
Please read the docs on using this API.
Related
I tested Spring Security as part of my Spring Boot Setup in version 6.0-M5, 6.0-RC1 and 6.0-RC2. I recognized a behavior change and wanted to ask whether this may be a bug. I return the CSRF token as a serialized JSON, but since RC1 the content of the token in the JSON is garbage.
My working code in Spring Boot 6 Milestone 5 still working as expected.
#RestController
public class CsrfController {
#GetMapping("/rest/user/csrf")
public CsrfToken csrf(CsrfToken token) {
return token;
}
}
In my use case I query the controller using a unit test.
#LocalServerPort
int serverPort;
#Autowired
private TestRestTemplate webclient;
#Test
public void getCsrf() {
ResponseEntity<String> entity = webclient.getForEntity("http://localhost:" + serverPort +
"/rest/user/csrf", String.class);
// ... here some code to get the token from the JSON body ...
assertTrue(result.matches("^[a-f0-9\\-]+$"));
This is the first query of the server. A session object between client and server is not established in past queries. This worked in M5 but stopped working in Spring Boot 6 RC1 and RC2
The following controller code made it work again in RC2:
#GetMapping("/rest/user/csrf")
public CsrfToken csrf(HttpServletRequest request, HttpServletResponse response) {
CsrfToken repoToken = tokenRepo.loadToken(request);
if (repoToken != null) {
return repoToken;
}
// required because it is required but ay not be initialized by the tokenRepo
request.getSession();
repoToken = tokenRepo.generateToken(request);
tokenRepo.saveToken(repoToken, request, response);
return repoToken;
}
If I tried the old code in RC2, I received on client side a malformed string. I did not receive a UUID styled token in my JSON serialized response body. I think it is related to the uninitialized session object.
Is this a bug or is an uninitialized session and a resulting not working CrsfToken specified behavior?
I think the issue is in the way I try to get and use the XSFR token.
Because I want to use an Angular frontend, I configured my token repository to provide the tokens via Cookie.
http.csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
This produces cookies the old UUID style. However the authentication expects the new tokens as generated by https://github.com/spring-projects/spring-security/issues/11960 . Probably the cookie mechanism still needs to be migrated until final Spring Boot 3.0.
I'm trying out JsonPatch but ran into an issue when I try to test it. My REST controller looks like this:
#RestController
#RequestMapping("/v1/arbetsorder")
class ArbetsorderController {
#PatchMapping(path ="/tider/{tid-id}", consumes = "application/json-patch+json")
public ResponseEntity<Persontid> patchTid(#PathVariable("tid-id") Long id, #RequestBody JsonPatch patch) {
Persontid modifieradPersontid = personTidService.patchPersontid(id, patch);
return new ResponseEntity<>(modifieradPersontid, HttpStatus.OK);
}
}
I'm testing this endpoint using this method:
#Test
void patchPersontid() {
String body = "{\"op\":\"replace\",\"path\":\"/resursID\",\"value\":\"Jonas\"}";
given()
.auth().basic(user, pwd)
.port(port)
.header(CONTENT_TYPE, "application/json-patch+json")
.body(body)
.when()
.patch("/v1/arbetsorder/tider/3")
.then()
.assertThat()
.statusCode(HttpStatus.OK.value())
.body("resursID", equalTo("Jonas"));
}
But this test fails because the status code is 500 instead of 200. I'm not reaching my endpoint.
I have tried using regular JSON and then everything works fine.
Can anyone help me understand why I'm not reaching my endpoint when using JsonPatch?
Apparently the body I send to the endpoint has to be an array in order for it to be converted to a JsonPatch object. Changing my body to:
String body = "[{\"op\":\"replace\",\"path\":\"/resursID\",\"value\":\"Jonas\"}]";
solved my problem!
I am new in spring boot and programming world .I am trying to post data on another server. I am using rest template to do that. I want to catch an exception when the server is not available .I am not sure how to do that .It would be helpful if anyone can just guide me where to look .I find so many examples but its getting more confusing.
Thanks in advance for your help.
You can use #Error Handler for this.You can use in your controller class to look around how this works when called.
#PostMapping("/hello")
public void hello(String msg)
{
RestTemplate restTemplate= new RestTemplate();
HttpEntity<String>reqEntity= new HttpEntity<>(msg);
restTemplate.postForEntity(" paste your server url here", reqEntity, String.class);
}
#ExceptionHandler(ConnectException.class)
#ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public void func()
{
System.out.println("I am not able to connect");
}
As you mentioned the server is not running so it will be handled by below mentioned function func on which #Exception handler is declared.You can read on #Exception handler.Certainly there are many different ways to do it.
I just started to learn Spring Boot today, and I wanted to create a GET/POST request for my Spring Boot Project. When I tried to access the URL that has the post request it shows 405 error saying that "Request method 'GET' not supported".
I think it is something wrong about my code for the POST request, but I don't know where I did wrong. I tried to search for the a tutorial that teaches how to write a proper GET/POST request, so I couldn't find anything good.
If you guys have any good website that teaches basic HTTP requests in Spring Boot, that will be great. I tried to find answers at StackOverflow, but I didn't find anything answers.
The Spring Boot project I have been using is the one from the official Spring.io website: https://spring.io/guides/gs/rest-service/
I wanted to call the POST request for my project so I have a better understanding of the HTTP.
Here is the source code for the controller:
package hello;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.web.bind.annotation.*;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;
#RestController
public class GreetingController {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
// GET Request
#RequestMapping(value="/greeting", method = GET)
public Greeting greeting(#RequestParam(value="name", defaultValue="World") String name) {
return new Greeting(counter.incrementAndGet(), name);
}
#RequestMapping(value = "/testpost", method = RequestMethod.POST)
public String testpost() {
return "ok";
}
}
Here is the source code for the Application:
package hello;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
And here is the source code for the Greeting Object
package hello;
public class Greeting {
private final long id;
private final String content;
public Greeting(long id, String content) {
this.id = id;
this.content = content;
}
public long getId() {
return id;
}
public String getContent() {
return content;
}
}
I can get the GET request working by using the "/greeting" URL.
I tried to access the "/testpost" url but it shows 405 error that the GET method is not supported.
There was an unexpected error (type=Method Not Allowed, status=405).
Request method 'GET' not supported
If you try to open the http://localhost:8080/testpost by directly opening in browser, it won't work because opening in browser makes a GET request.
I am not sure how you are trying to do a post request, I tried to do the same post request from postman and able to get the response. Below is the screenshot.
It looks like you are trying to make post request directly from web browser which will not work.
When you hit a URL directly from web browser address bar, it is considered as GET request. Since in your case, there is no GET API as /testpost , it is giving error.
Try to use rest client such as Postman or curl command to make post request.
I tried your post end-point with postman and it is working properly. PFA snapshot for your reference.
Hope this helps.
From where you are trying POST request. If from browser windows you calling POST call, then it will not work, browser will send only GET request. Have you tried from postman or from UI side. It will work.
We are developing a contract-first WebService using spring-ws 2.2.0. We are trying to manage the authentication using a custom tag, named AuthToken, located in the SoapHeader.
The AuthToken has the following structure:
<authToken>
<username>USERNAME</xa:username>
<password>PASSWORD</xa:password>
</authToken>
We are able to generate a WSDL schema containing the specified custom authentication tag inside the SoapHeader.
The problem is that when the client performs the call towards our server we are not able to unmarshal the AuthToken tag (located in the SoapHeader) in our Ws Endpoint implementation.
Using the #RequestPayload annotation in the binding method signature (handleMethodRequest as specified in the example below), we are able to access the unmarshalled payload content (located in the SoapBody).
We tried to make the same thing with the SoapHeader content without success.
In the following code examples we show you what we would like to obtain:
1
#PayloadRoot(namespace = NAMESPACE_URI, localPart = "methodRequest")
#ResponsePayload
public MethodResponse handleMethodRequest(#RequestPayload MethodRequest request, #SoapHeader(value = "authToken") AuthToken authToken) { }
2
#PayloadRoot(namespace = NAMESPACE_URI, localPart = "methodRequest")
#ResponsePayload
public MethodResponse handleMethodRequest(#RequestPayload MethodRequest request, AuthToken authToken) { }
3
#PayloadRoot(namespace = NAMESPACE_URI, localPart = "methodRequest")
#ResponsePayload
public MethodResponse handleMethodRequest(#RequestPayload MethodRequest request, org.springframework.ws.soap.SoapHeader header) { }
4
#PayloadRoot(namespace = NAMESPACE_URI, localPart = "methodRequest")
#ResponsePayload
public MethodResponse handleMethodRequest(#RequestPayload MethodRequest request, MessageContext messageContext) { }
In case 1, 2 we obtain the following error:
No adapter for endpoint [MethodResponse EndpointImplementation.handleMethodRequest(MethodRequest, AuthToken) throws java.lang.Exception]: Is your endpoint annotated with #Endpoint, or does it implement a supported interface like MessageHandler or PayloadEndpoint?
In case 3, 4 we have no errors but we are not able to handle SoapHeader or MessageContext (respectively in case 3 and 4) to reach our purposes, accessing the AuthToken to retrieve username and password sub element.
Looking for a solution in the web we found that many people having the same problem uses Spring Interceptors to handle the authentication.
Following the "Interceptors-way" we should access the AuthToken inside the interceptor. Unfortunately we need to use AuthToken field inside handleMethodRequest method for other purposes, for example loading user specific data, not accessible outside handleMethodRequest.
Therefore we cannot follow this way because we need to refer user specific data inside the handleMethodRequest method.
Does anyone know how can we solve the problem? Thanks in advance.
For that use case, the only supported combination of annotation and parameter type is #SoapHeader and SoapHeaderElement. Spring-WS currently doesn't support unmarshalling headers.
A hacky way of getting the value from interceptor to the handleMethodRequest is using a static ThreadLocal instance. Since the same thread that invokes the interceptor also invokes the handleMethodRequest you can use
ThreadLocal.set(AuthToken); // in interceptor.
ThreadLocal.get();// in handler and then clear it after use.
Also, I noticed that #SoapHeader(value = "{authToken") in your example does not have } is that a typo here or in your code?