I have two tokens one is brandwiseBearerToken which is a string and another is thirdPartyPaymentGatewayToken it belongs form my POJO class, and I want to pass these two values as dynamic. but in my case, I pass as hard-coded how I can make it dynamic. for your reference, I share my code.
I want to dynamic exact at this point
String thirdPartyPaymentGatewayTokenJson = ow.writeValueAsString(thirdPartyPaymentGatewayToken);
RequestBody body = RequestBody.create(mediaType,thirdPartyPaymentGatewayTokenJson);
I don't want to pass hard-coded data
public ThirdPartyPaymentGatewayResponse getThirdPartyPaymentGatewayToken(ThirdPartyPaymentGatewayToken thirdPartyPaymentGatewayToken, String managedBy)
throws AuthenticationException, UnknownHostException, BadRequestException {
String brandwiseBearerToken = authenticationToken();
String thirdPartyPaymentGatewayTokenJson = ow.writeValueAsString(thirdPartyPaymentGatewayToken);
RequestBody body = RequestBody.create(mediaType, thirdPartyPaymentGatewayTokenJson);
Request request = new Request.Builder().url(brandwiseThirdPartypaymentGatewayURL)
.post(body)
.addHeader("Content-Type", "application/json")
.addHeader("Bearer", brandwiseBearerToken)
.build();
Response response = client.newCall(request).execute();
ResponseBody responseBody = response.body();
JsonObject jsonObject = new Gson().fromJson(responseBody.string(), JsonObject.class);
JsonElement error = jsonObject.get("Message");
}
```
Related
My code is below in brief :
private void havayı_gösterActionPerformed(java.awt.event.ActionEvent evt) {
String WEATHER_URL = "https://api.collectapi.com/weather/getWeather?data.lang=tr&data.city="+şehir_ismi.getText();
//REQUEST GÖNDERME
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = (HttpRequest) HttpRequest.newBuilder()
.GET()
.header("content-type", "application/json")
.header("authorization", "apikey myapikey")
.uri(URI.create(WEATHER_URL))
.build();
//REQUESTE CEVAP
try {
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
String content = response.body();
JSONParser parser = new JSONParser();
Object obj;
obj = parser.parse(content);
JSONArray array = new JSONArray();
array.add(obj);
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String req_result = gson.toJson(array.get(0));
String text;
text = req_result.replaceAll("\"", "")
.replaceAll("\\{", "")
.replaceAll("result:", "")
.replaceAll("\\},", "")
.replaceAll("\\,", "")
.replaceAll("\\]","")
.replaceAll("\\[","")
.replaceAll("success: true","")
.replaceAll("\\}","");
havayı_listele.setText(text);
I want to show a pretty printed data in the java swing, but attribute "icon" causes unreadability. Also Java does not support svg files. What's the easiest way to get rid of this problem ? Here is my screenshot :
I am using Spring RestTemplate client to do a POST call to another application which handles this request as HTTpServletRequest.
Problem is HTTpServletRequest is expecting a key value pair e.g.
String xmlString = request.getParameter("xml12")
//xmlString should be "`<parent><child></child></parent>`" but coming as null.
Here is the code snippet of both ends -
My app -
String data = "`<parent><child></child></parent>`"
HttpHeaders header = new HttpHeaders()
header.setContentType(MediaType.APPLICATION_XML)
Map<String,String> bodyParamMap = new HashMap<String,String>();
bodyParamMap.put("xml123",data)
String reqBodyData = new ObjectMapper().writeValuesAsString(bodyParamMap)
HttpEntity<String> entity = new HttpEntity<String>(reqBodyData,header)
RestTemplate rt = new RestTemplate()
String response = rt.postForObject("url",entity,String.class)
//Getting response as 500
Other app -
HttpServletRequest request = new HttpServletRequest()
String xmlString = request.getParameter("xml123")
// xmlString is null
I just want to know my mistake and how to pass my data string to post request so that request.getParameter("xml123") receives my data xml as String.
I want to send post request from my Android apps to Spring Boot. I use okhttp to send the HTTP post request in JSON. The code is like this:
Every time I send post request using the Android request I got 400 bad request parameter 'name' is not present","path":"/newcustomer". But when I use postman it works.
Java
----------------------------------------------------------------
Log.d("okhttphandleruserreg", "called");
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
JSONObject jsonObject = new JSONObject();
try{
jsonObject.put("name", name);
jsonObject.put("email", email);
jsonObject.put("username", username);
jsonObject.put("password", password);
jsonObject.put("month", month);
jsonObject.put("dayOfMonth", dayOfMonth);
} catch (JSONException e) {
e.printStackTrace();
}
RequestBody body = RequestBody.create(JSON, jsonObject.toString());
Request.Builder builder = new Request.Builder();
builder.url(params[0]);
builder.post(body);
Request request = builder.build();
Spring Boot
-----------------------------------------------------------------
#RequestMapping(value = "/newcustomer", method= RequestMethod.POST)
public Customer newCust(#RequestParam(value="name") String name,
#RequestParam(value="email") String email,
#RequestParam(value="username") String username,
#RequestParam(value="password") String password,
#RequestParam(value="month") int month,
#RequestParam(value="dayOfMonth") int dayOfMonth
)
The way you have implemented your back-end /newcustomer API suggests you are expecting the request payload to be raw request params within the request form data.
Assuming the server side API is your contract, thus should remain as is, your client code should be updated as follows:
Log.d("okhttphandleruserreg", "called");
// here you create your request body as as a Form one
RequestBody formBody = new FormBody.Builder()
.add("name", "test")
.add("email", "test#domain.com")
.add("username", "test")
.add("username", "test")
.add("month", "january")
.add("dayOfMonth", "1")
.build();
Request request = new Request.Builder()
.url(params[0])
.post(formBody)
.build();
// call your request
You are using Request Params in Spring Boot but whereas in Android code you sending that as Request Body.
Please change any one of the above. Better if you use RequestBody in both places.
class Customer
{
String name:
String email:
String username;
String password;
int month;
int dayofthemonth;
//getter and setters
}
public Customer newCust(#RequestBody Customer newcustomer)
{
}
I have two services (one service calls an end point localhost:7000/create to send a json and want expects a json )
Called service is something like this (Data is pojo class) :
#RequestMapping(value="/create",consumes="application/json",produces = "application/json",method = RequestMethod.POST)
#ResponseBody
public Data responseForPayload(#RequestBody String data) {
Data data= new Data();
data.setAccountId("45");
return data;
}
and the calling service restTemplate call is like this (running in :9000):
String ResourceUrl = "http://localhost:7000/create";
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
List list= new ArrayList();
list.add(MediaType.APPLICATION_JSON);
HttpEntity httpEntity = new HttpEntity(downstreamPayload, headers);
ResponseEntity<JSONObject> response = restTemplate.exchange(ResourceUrl,
HttpMethod.POST, httpEntity, JSONObject.class);
but i am getting response as {}, when I use string instead of JSON it works fine. I used postman to just to call the 127.0.0.1:7000/create, it worked fine with returning the expected as json
What is my mistake here?
Thanks
I'm having a problem using Spring restTemplate.
For now i'm sending a PUT request for a restful service and that restful service send me back important informations in response.
The question is that restTemplate.put are a void method and not a string so i can't see that response.
Following some answers i've change my method and now i'm using restTemplate.exchange, here are my method:
public String confirmAppointment(String clientMail, String appId)
{
String myJsonString = doLogin();
Response r = new Gson().fromJson(myJsonString, Response.class);
// MultiValueMap<String, String> map;
// map = new LinkedMultiValueMap<String, String>();
// JSONObject json;
// json = new JSONObject();
// json.put("status","1");
// map.add("data",json.toString());
String url = getApiUrl() + "company/" + getCompanyId() + "/appointment/" + appId + "?session_token=" + r.data.session_token;
String jsonp = "{\"data\":[{\"status\":\"1\"}]}";
RestTemplate rest = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/json");
headers.add("Accept", "*/*");
HttpEntity<String> requestEntity = new HttpEntity<String>(jsonp, headers);
ResponseEntity<String> responseEntity =
rest.exchange(url, HttpMethod.PUT, requestEntity, String.class);
return responseEntity.getBody().toString();
}
Using the method above, i receive a 400 Bad Request
I know my parameters, url and so, are just fine, cause i can do a restTemplate.put request like this:
try {
restTemplate.put(getApiUrl() + "company/" + getCompanyId() + "/appointment/" + appId + "?session_token=" + r.data.session_token, map);
} catch(RestClientException j)
{
return j.toString();
}
The problem (like i said before) is that the try/catch above does not return any response but it gives me a 200 response.
So now i ask, what can be wrong?
Here's how you can check the response to a PUT. You have to use template.exchange(...) to have full control / inspection of the request/response.
String url = "http://localhost:9000/identities/{id}";
Long id = 2l;
String requestBody = "{\"status\":\"testStatus2\"}";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> entity = new HttpEntity<String>(requestBody, headers);
ResponseEntity<String> response = template.exchange(url, HttpMethod.PUT, entity, String.class, id);
// check the response, e.g. Location header, Status, and body
response.getHeaders().getLocation();
response.getStatusCode();
String responseBody = response.getBody();
You can use the Header to send something in brief to your clients. Or else you can use the following approach as well.
restTemplate.exchange(url, HttpMethod.PUT, requestEntity, responseType, ...)
You will be able to get a Response Entity returned through that.
Had the same issue. And almost went nuts over it. Checked it in wireshark: The problem seems to be the escape characters from the request body:
String jsonp = "{\"data\":[{\"status\":\"1\"}]}";
The escape character (backslash) is not resolved. The String is sent with the backslashes, which is obviously not a valid json and therefore no valid request(-body).
I bypassed this by feeding everything in with an Object, that is mapping all the properties.