Conditional Base pass dynamic value inside request body - java

I want to pass dynamic value inside request body in my case I pass
thirdpartypaymentGatewayToken in two place inside request body and an
other place requestString as requestBody but I want make single
function and pass values inside request body dynamic. for your
reference I post my old code and new code.
Here my old code
public ThirdPartyPaymentGatewayResponse getThirdPartyPaymentGatewayToken(ThirdPartyPaymentGatewayToken thirdPartyPaymentGatewayToken, String managedBy)
throws AuthenticationException, UnknownHostException, BadRequestException {
String brandwiseBearerToken = getBrandwiseAuthenticationToken();
ThirdPartyPaymentGatewayResponse thirdPartyPaymentGatewayResponse = new ThirdPartyPaymentGatewayResponse();
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");
}
> second function
public ThirdPartyPaymentGatewayResponse getThirdPartyPaymentGatewayToken(ThirdPartyPaymentGatewayToken thirdPartyPaymentGatewayToken, String managedBy)
throws AuthenticationException, UnknownHostException, BadRequestException {
String brandwiseBearerToken = getBrandwiseAuthenticationToken();
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");
/** rest of code*/
}
third function different than other two
private String getBrandwiseAuthenticationToken() throws UnknownHostException, AuthenticationException {
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/json");
String requestString = "{\"LoginName\": \"" + brandwiseAuthUsername + "\",\"Password\": \""+ brandwiseAuthPassword + "\"}";
RequestBody body = RequestBody.create(mediaType, requestString);
Request request = new Request.Builder().url(brandwiseAuthenticationURL)
.post(body)
.addHeader("Content-Type", "application/json")
.build();
Response response = client.newCall(request).execute();
ResponseBody responseBody = response.body();
JsonObject jsonObject = new Gson().fromJson(responseBody.string(), JsonObject.class);
}
To overcome from this issue I do this way but I am not able make
request body as dynamic. Here my new code
private JsonObject gateWayToken(String url,String brandwiseBearerToken,
ThirdPartyPaymentGatewayToken thirdPartyPaymentGatewayToken ) throws IOException, AuthenticationException{
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String requestString = "{\"LoginName\": \"" + brandwiseAuthUsername + "\",\"Password\": \""+ brandwiseAuthPassword + "\"}";
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body=null;
//dynamic value accept by body
if(!Strings.isNullOrEmpty(requestString)) {
String brandwiseBearerPaymentGatewayTokenJson = ow.writeValueAsString(requestString);
body = RequestBody.create(mediaType,brandwiseBearerPaymentGatewayTokenJson);
}else {
String thirdPartyPaymentGatewayTokenJson = ow.writeValueAsString(thirdPartyPaymentGatewayToken);
body = RequestBody.create(mediaType,thirdPartyPaymentGatewayTokenJson );
}
//if user is authenticated then header part will show
Request request=null;
if (brandwiseBearerToken != null && StringUtils.isNotEmpty(brandwiseBearerToken)) {
request =new Request.Builder().url(url).post(body)
.addHeader("Content-Type", "application/json")
.addHeader("Bearer", brandwiseBearerToken)
.build();
} else {
request=new Request.Builder().url(url).post(body)
.addHeader("Content-Type", "application/json")
.build();
}
Response response = client.newCall(request).execute();
ResponseBody responseBody = response.body();
return new Gson().fromJson(responseBody.string(), JsonObject.class);
}
I want to dynamic exact at this point
if(!Strings.isNullOrEmpty(requestString)) {
String brandwiseBearerPaymentGatewayTokenJson = ow.writeValueAsString(requestString);
body = RequestBody.create(mediaType,brandwiseBearerPaymentGatewayTokenJson);
}else {
String thirdPartyPaymentGatewayTokenJson = ow.writeValueAsString(thirdPartyPaymentGatewayToken);
body = RequestBody.create(mediaType,thirdPartyPaymentGatewayTokenJson );
}
Check Passing values inside ReqestBody

Related

OkHttp implement unit test?

I have a function using OkHttp to get data from third party api
public List<AuditData> getAuditData(OkHttpClient client, int retLabelId, int countryId, int periodId, int versionNo, String URL, String token) throws IOException {
DefaultGraphQLClient graphQLClient = new DefaultGraphQLClient(URL);
String query = QueryUtils.getAuditDataQuery(retLabelId, countryId, periodId, versionNo, PartitionUtil.getReadPartition(token));
GraphQLResponse response = graphQLClient.executeQuery(query, new HashMap<>(), "", (url, headers, body) -> {
Request request = new Request.Builder()
.header("Authorization", "Bearer " + token)
.url(url)
.post(RequestBody.create(okhttp3.MediaType.parse("text/x-markdown"), body))
.build();
try {
Response responseOkHttp = client.newCall(request).execute();
return new HttpResponse(responseOkHttp.code(), responseOkHttp.body().string());
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
);
return response.extractValueAsObject("data.auditData[*]", new TypeRef<List<AuditData>>() {
});
}
I want to write unit test for the function above. I have tried with MockWebServer and it doesn't work.
MockResponse response = new MockResponse()
.addHeader("Content-Type", "application/json; charset=utf-8")
.addHeader("Cache-Control", "no-cache")
.setBody(jsonResponse);
server.enqueue(response);
OkHttpClient client = new OkHttpClient();

How to send DELETE request using HttpClient

how can I send an http DELETE request to this
using HttpClient object or something similar?
This is my code for GET and POST requests:
public class Main {
public static void main(String[] args) throws IOException, InterruptedException {
//jsonGetRequest();
//jsonPostRequest();
}
public static void jsonGetRequest() throws IOException, InterruptedException {
final String URL = "https://vbzrei5wpf.execute-api.us-east-1.amazonaws.com/test/pets";
HttpClient httpClient = HttpClient.newHttpClient();
HttpRequest httpRequest = HttpRequest
.newBuilder()
.GET()
.header("accept", "application/json")
.uri(URI.create(URL))
.build();
HttpResponse<String> httpResponses = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
//System.out.println(httpResponses.body()); // stampa l'intero file JSON
// Parsing JSON into Objects
ObjectMapper objectMapper = new ObjectMapper();
List<Pet> pets = objectMapper.readValue(httpResponses.body(), new TypeReference<List<Pet>>() {
});
//pets.forEach(System.out::println); oppure
for (Pet pet : pets) {
System.out.println(pet.getId() + ", " + pet.getType() + ", " + pet.getPrice());
}
}
public static void jsonPostRequest() throws IOException, InterruptedException {
final String URL = "https://vbzrei5wpf.execute-api.us-east-1.amazonaws.com/test/pets";
final Map<String, Object> values = new HashMap<>();
values.put("type", "octopus");
values.put("price", 12.99);
ObjectMapper objectMapper = new ObjectMapper();
String requestBody = objectMapper.writeValueAsString(values);
HttpClient httpClient = HttpClient.newHttpClient();
HttpRequest request = HttpRequest
.newBuilder()
.uri(URI.create(URL))
.POST(HttpRequest.BodyPublishers.ofString(requestBody))
.build();
HttpResponse<String> response = httpClient.send(request,
HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
}
public static void jsonDeleteRequest() {
final String URL = "https://vbzrei5wpf.execute-api.us-east-1.amazonaws.com/test/pets";
// TODO...
}
}
A DELETE request is sent the same way as GET, just use the "DELETE" method instead of "GET":
HttpRequest httpRequest = HttpRequest
.newBuilder()
.DELETE()
.uri(URI.create(URL))
.build();
If you want to delete an object use #Joni's answer. If you want to specify the id of the object, add /<id> to your url
https://vbzrei5wpf.execute-api.us-east-1.amazonaws.com/test/pets/1 would be the url to delete the element with the id 1

Getting bad response trying to send a request

I'm trying to send a request to a NodeJS server, I'm always getting Bad Request message with status code 400.
I tried using Postman to check if the problem was on the server, but in Postman it worked correctly.
I'm using OkHttp and trying to send a request like this:
private Request request;
private final OkHttpClient client = new OkHttpClient();
private void makePost(String nameOfProduct, String serialOfProduct, String priceOfProduct, String gender, String uriList, String colors, String sizes) {
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("name", nameOfProduct)
.addFormDataPart("serial",serialOfProduct)
.addFormDataPart("price",priceOfProduct)
.addFormDataPart("gender",gender)
.addFormDataPart("color", colors)
.addFormDataPart("size", sizes)
.addFormDataPart("imagesUri",uriList)
.build();
Log.d("COLROS", colors);
request = new Request.Builder()
.url("http://10.0.2.2:4000/products/add")
.header("Content-Type", "application/json")
.post(requestBody)
.build();
try{
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
}
Headers responeHeaders = response.headers();
for (int i = 0; i < responeHeaders.size(); i++) {
Log.d("iu", "makePost: "+responeHeaders.name(i) + ": " + responeHeaders.value(i));
}
Log.d("iu", "makePost: "+response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
You are sending Form data (application/x-www-form-urlencoded) but setting the header as json
Try to remove the line:
.header("Content-Type", "application/json")
and use:
.header("Content-Type", "application/x-www-form-urlencoded")
To send JSON data, you must build a JSON string. I'll use Gson library here, make sure you include it in your module level gradle file as follows:
implementation 'com.google.code.gson:gson:2.8.6'
Next you need a class to serialize into JSON:
public class Order {
public String name;
public String serial;
public int price;
public String gender;
//Other fields go here...
//This empty constructor is required by Gson
public Order() {}
}
Now you build an object of this class as you require:
private void makePost(String nameOfProduct, String serialOfProduct, String priceOfProduct, String gender, String uriList, String colors, String sizes) {
Order order = new Order();
order.name = nameOfTheProduct;
order.price = priceOfTheProduct;
//Fill in other fields here...
//Now get a JSON data string from this object using Gson:
Gson gson = new Gson();
String jsonData = gson.toJson(order);
public static final MediaType mediaTypeJSON = MediaType.get("application/json; charset=utf-8");
RequestBody requestBody = RequestBody.create(mediaTypeJSON, jsonData);
//Build the request
Request request = new Request.Builder()
.url("http://10.0.2.2:4000/products/add")
.post(requestBody)
.build();
//Finally send the request as you already do in your code
//Using the call: Response response = client.newCall(request).execute();
}

cannot resolve method create 'com.google.common.net.MediaType,java.lang.String)

I want to send a device to device Firebase notification using OkHttp 3, but am getting the following error when posting the JSON:
cannot resolve method create 'com.google.common.net.MediaType,java.lang.String)
Here is my code:
final String legacyServerKey = "";
final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
JSONObject json = new JSONObject();
JSONObject dataJson = new JSONObject();
dataJson.put("body", "Hi this is sent from device to device");
dataJson.put("title", "dummy title");
json.put("notification", dataJson);
json.put("to", reg_token);
RequestBody body = RequestBody.create(JSON, json.toString());
Request request = new Request.Builder()
.header("Authorization", "key=" + legacyServerKey)
.url("https://fcm.googleapis.com/fcm/send")
.post(body)
.build();
try {
Response response = client.newCall(request).execute();
String finalResponse = response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
It looks like you imported com.google.common.net.MediaType. You need okhttp3.MediaType

Force.com Apex code counter part or equivalent code to Java

I am not certain if I am on the right path. Since I am not getting any data with the HTTP Request. I needed to convert this java code into force.com apex for me to be able to use a WTS web service.
public static HttpEntity getRequestEntity()
{
JSONArray jsonArr = new JSONArray();
HttpEntity entity = null;
JSONObject jsonElement = new JSONObject();
JSONObject jsonObj = new JSONObject();
JSONObject jsonObj1 = new JSONObject();
jsonElement.put("tenant",jsonObj);
jsonObj.put("companyKey",companyName);
String json = jsonElement.toJSONString();
try {
entity = new StringEntity(json);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return entity;
}
private static void GetEnabledUsers(String responseContent) throws ParseException, ClientProtocolException, IOException {
String url = "<endpoint>/services/UserService1.svc/GetEnabledUsers";
// Create an http client to perform the http communication
CloseableHttpClient httpClient = HttpClients.createDefault();
// Http request to specific web service. Request will be given to client
HttpPost request = new HttpPost(url);
// Create credentials for the authentication
CredentialsProvider provider = new BasicCredentialsProvider();
UsernamePasswordCredentials credential = new UsernamePasswordCredentials(companyName+'\\'+userName, password);
provider.setCredentials(AuthScope.ANY, credential);
HttpClientContext localContext = HttpClientContext.create();
localContext.setCredentialsProvider(provider);
// Make the actual http request
HttpPost httpRequest = new HttpPost(url);
HttpEntity requestEntity = getRequestEntity();
if(requestEntity != null) {
httpRequest.setHeader("Content-type", "application/json");
httpRequest.setEntity(requestEntity);
}
CloseableHttpResponse response = httpClient.execute(httpRequest, localContext);
HttpEntity entity = response.getEntity();
String responseContent1 = EntityUtils.toString(entity);
System.out.println(responseContent1);
}
This is what I have so far:
String userName= '<userName>';
String password= '<password>';
String companeyKey = '<companeyKey>';
JSONGenerator jsonGenerator = JSON.createGenerator(true);
jsonGenerator.writeStartObject();
jsonGenerator.writeFieldName('tenant');
jsonGenerator.writeStartObject();
jsonGenerator.writeStringField('companeyKey', '<companeyKey>');
jsonGenerator.writeEndObject();
jsonGenerator.writeEndObject();
requestBody = jsonGenerator.getAsString();
Blob headerValue = Blob.valueOf(userName + ':' + password);
HttpRequest requestEntity = new HttpRequest();
String authHeader = 'BASIC ' + EncodingUtil.base64Encode(headerValue);
requestEntity.setMethod('POST');
requestEntity.setEndPoint('<endpoint>/services/UserService1.svc/GetEnabledUsers');
requestEntity.setHeader('Content-Type', 'application/json');
requestEntity.setHeader('Authorization', authHeader);
requestEntity.setBody(requestBody);
Http http = new Http();
HTTPResponse responseEntity = http.send(requestEntity);
system.debug(responseEntity);
On difference seems to be around how the username is constructed for the auth parameter, change
Blob headerValue = Blob.valueOf(userName + ':' + password);
to
Blob headerValue = Blob.valueOf(companyKey + '\\' + userName + ':' + password);

Categories

Resources