I am new to using Spring mvc4 annotation . In all i want to do is using spring mvc as a web service . so i would be thankful if anyone could provide me a solution for it.
My android code is as:
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
HttpConnectionParams.setSoTimeout(httpParams, 5000);
HttpClient httpclient = new DefaultHttpClient(httpParams);
HttpPost httppost = new HttpPost( "http://localhost:8080/datarequest");
JSONObject json = new JSONObject();
json.put("action", "check_login");
json.put("username","name");
json.put("password", "password");
JSONArray postjson = new JSONArray();
postjson.put(json);
httppost.setHeader("json", json.toString());
httppost.getParams().setParameter("jsonpost", postjson);
System.out.println(postjson);
HttpResponse response = httpclient.execute(httppost);
so far i wrote the web service as:
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
#Controller
#RequestMapping("/datarequest")
public class HelloController {
#RequestMapping(method = RequestMethod.GET)
public String getMethod(ModelMap model) {
System.out.println("GET");
return "hello";
}
#RequestMapping(method = RequestMethod.POST, produces = "application/json")
public String getMethod(ModelMap model) {
System.out.println("POST");
System.out.println("here i want to print json data send from the android ");
return "hello";
}
}
You can use #RequestBody and map it to required class structure. You can refer this SO question #RequestBody and #ReponseBody spring.
To test, you can map it to String. See below example.
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RequestHeader;
#RequestMapping(method = RequestMethod.POST, produces = "application/json")
public #ResponseBody String getMethod(#RequestHeader(value="json") String headerStr) {
System.out.println("POST");
System.out.println(s);
return "hello";
}
You can add below maven entry in your pom.
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.1</version>
</dependency>
Related
I started building a spring boot RestController following documentation.
Here is my RestController code.
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
#RestController
public class JsonResponseController {
#RequestMapping(value="/json", method = RequestMethod.GET)
#ResponseBody
public ResponseEntity<List<JSONObject>> clearing(#RequestParam(value = "count", defaultValue = "22") Integer count) {
System.out.println(new String("YOU CALLED THE ENDPOINT FOR CLEARING FILES."));
System.out.println("count request param:" + count);
List<JSONObject> list = new ArrayList<JSONObject>();
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/json");
for (int i = 0; i < count; i++) {
JSONObject entity = new JSONObject();
entity.put("id", i);
list.add(entity);
}
System.out.println( list.toString() );
return ResponseEntity.ok(list);
}
}
But my response looks always like that:
[{"empty":false},{"empty":false},{"empty":false},{"empty":false},{"empty":false},{"empty":false}]
Any help?
I'm very new to web-service dev and I'm trying to make a POST request to an API using Jersey. The issue is I think I'm mixing documentation and example I'm finding online between client & server. I'm pretty sure that it's simple but I can't figure out why my code is failing.
Here is my main Class :
import deliveryPayload.Payload;
import jakarta.ws.rs.*;
import jakarta.ws.rs.client.*;
import jakarta.ws.rs.core.HttpHeaders;
import jakarta.ws.rs.core.MediaType;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.UriBuilder;
import org.apache.commons.lang3.StringUtils;
import responsePayload.ResponsePayload;
import java.net.URI;
import java.util.*;
#Path("/hook")
public class Hook {
private static final String apiToken = "myToken";
private static final String domain = "url";
private static final String apiUrl = "https://" + domain + "/api/v1/";
#POST
#Consumes(MediaType.APPLICATION_JSON)
public Response eventHook(String body, #HeaderParam("Pass") String password) {
ObjectMapper objectMapper = new ObjectMapper();
Payload payload = new Payload();
try {
payload = objectMapper.readValue(body, Payload.class);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
EventsItem event = payload.getData().getEvents().get(0);
Actor actor = event.getActor();
Response response = ClientBuilder.newClient()
.target(getBaseURI())
.path("apps/" + "someID" + "/users")
.request(MediaType.APPLICATION_JSON)
.header(HttpHeaders.AUTHORIZATION, apiToken)
.post(Entity.entity(actor, MediaType.APPLICATION_JSON));
return response;
}
}
I'm getting this error Parse Error: The response headers can't include "Content-Length" with chunked encoding when using Postman.
Thanks for any help !
I am getting the error 'A JSONObject text must begin with '{' at 1 [character 2 line 1]'
while calling NewsAPI using RestTemplate of Spring.
Below is the snippet code I have used to get response. I am able to get the response string but unable to parse it through org.JSON class
import java.util.Arrays;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
public class APITest {
final private static String NEWSAPI_URI="https://newsapi.org/v2/top-headlines";
final private static String API_TOKEN_VAL=“*****************”;
final private static String API_TOKEN="apiKey";
final private static String COUNTYRY="Country";
final private static String COUNTYRY_VAL="US";
public static void main(String[] args) {
RestTemplate restTemplate=new RestTemplate();
UriComponentsBuilder builder=UriComponentsBuilder.fromHttpUrl(NEWSAPI_URI)
.queryParam(API_TOKEN, API_TOKEN_VAL)
.queryParam(COUNTYRY, COUNTYRY_VAL)
;
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
ResponseEntity<String> responseEntity=restTemplate.exchange(builder.toUriString(), HttpMethod.GET, entity, String.class);
//parsing responseEntity
HttpStatus httpStatus=responseEntity.getStatusCode();
String responseString=responseEntity.getBody();
System.out.println(responseString);
if(httpStatus.is2xxSuccessful()) {
JSONObject jsonObject=new JSONObject(responseString.trim());
JSONArray articles=jsonObject.getJSONArray("articles");
//System.out.println(articles.getJSONObject(0).get("content"));
for(int it=0;it<articles.length();it++) {
JSONObject articleObject=articles.getJSONObject(it);
System.out.println(articleObject.getString("content"));
}
}
}
#Bean
public RestTemplate getRestTemplate() {
return new RestTemplate();
}
}
friend, I'm using RestController from spring data to consume data from external API.
When I use PostMan to get data, I get this 404 error code.
But if I use direct URL with a header on POSTMAN I get the correct data and response code 200
Could you please help me
Console Intelij
2018-11-13 17:30:42.334 WARN 11820 --- [nio-8080-exec-2] o.s.web.servlet.PageNotFound : No mapping for GET /toto
This my Controller Class
package com.controller;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import javax.json.Json;
#RestController
#CrossOrigin("*") // pour gere les erreu d'ente ex: Orig
public class FlightRestServives {
private static Logger logger = Logger.getLogger(FlightRestServives.class.getName());
#Autowired
private RestTemplate restTemplate;
String serviceURL = "https://api.klm.com/opendata/flightoffers/reference-data?country=NL";
public FlightRestServives() {
}
//Consuming a service by GET method
// #GetMapping("/test")
#RequestMapping(
value = "/toto",
headers = {
"api-key=xmc3vburw886j9zqcsfrdu2t",
"AFKL-TRAVEL-Country=NL",
"AFKL-TRAVEL-Host=KL",
"X-Originating-IP=46.193.67.48"}
/*produces = "application/json",
consumes = "application/json",
headers = {
"api-key=xmc3vburw886j9zqcsfrdu2t",
"AFKL-TRAVEL-Country=NL",
"AFKL-TRAVEL-Host=KL",
"X-Originating-IP=46.193.67.48"}*/
)
public Json getAvailableOperations() {
logger.debug("Flight");
HttpHeaders headers = new HttpHeaders();
headers.add("api-key", "Keyyy");
headers.add("AFKL-TRAVEL-Country", "NL");
headers.add("AFKL-TRAVEL-Host", "KL");
headers.add("X-Originating-IP", "46.193.67.48");
HttpEntity requestEntity = new HttpEntity(headers);
logger.debug("request entities are: " + requestEntity);
return restTemplate.getForObject(serviceURL, Json.class);
/*return restTemplate
.exchange(
serviceURL,
HttpMethod.GET,
requestEntity,
Json.class
);*/
}
}
I need some help with writing a controller to consume a JSON response from a payment system (Realex).
So far, I have the following from the Realex documentation but can't figure out how to write the controller - i'm new to Spring Boot/Spring MVC.
RealexHpp realexHpp = new RealexHpp("Shared Secret");
HppResponse hppResponse = realexHpp.responseFromJson(responseJson);
// responseJson will be the Java variable containing the JSON response string
String result = hppResponse.getResult();
String message = hppResponse.getMessage();
String authCode = hppResponse.getAuthCode();
So far, i have written:
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.realexpayments.hpp.sdk.RealexHpp;
import com.realexpayments.hpp.sdk.domain.HppResponse;
#Controller
public class PaymentController {
#RequestMapping(value = "/enrolment/confirmation", method = RequestMethod.GET, consumes = "text/plain")
public String process(#RequestBody String responseJson, Model model) throws Exception {
RealexHpp realexHpp = new RealexHpp("secret");
HppResponse hppResponse = realexHpp.responseFromJson(responseJson);
// responseJson will be the Java variable containing the JSON response string
String result = hppResponse.getResult();
String message = hppResponse.getMessage();
String authCode = hppResponse.getAuthCode();
System.out.println("Result: "+result);
System.out.println("Message: "+message);
System.out.println("AuthCode: "+authCode);
model.addAttribute("result", result);
model.addAttribute("message", message);
model.addAttribute("authcode", authCode);
return "enrolment/confirmation";
}
}
Looks like Spring MVC isn't the right tool here.
See: https://github.com/realexpayments/rxp-hpp-java
It's expecting you to use their SDK to generate the repsonseJson:
HppRequest hppRequest = new HppRequest()
.addAmount(100)
.addCurrency("EUR")
.addMerchantId("merchantId");
RealexHpp realexHpp = new RealexHpp("mySecret");
String requestJson = realexHpp.requestToJson(hppRequest);
You might want to be using Spring MVC to capture the parameters for the request.