How to print http request with all the params? - java

This is a portion of code(somebody else wrote) that I am trying to understand. I want to print the request sent, but couldn't figure out a way to print url with all the params here.
//Obtain Response object returned by POST call to API with parameters passed in as HashMap
public static Response getPOSTResponse(String query, String endpoint, HashMap<String, String> params) {
//Initialize variables - for url and for data to be sent in POST request (need new hashmap for data due to type)
String base_url = getUrl(endpoint);
StringBuffer url = new StringBuffer();
HashMap<String, List<Integer>> postData = new HashMap<String, List<Integer>>();
url.append(base_url + "?");
params.forEach((k, v) -> {
String key = k;
String value = (params.get(k));
if (key.contains("list")) {
postData.put(key, Collections.singletonList(Integer.parseInt(value)));
} else { //should handle case for any [other] POST urls using parameters
url.append(key);
url.append("=");
url.append(value);
url.append("&");
}
});
final RequestSpecification sender = given().headers("Content-Type", ContentType.JSON,
"Accept", ContentType.JSON);
return sender.when().body(postData).post(url.toString()).then().contentType(ContentType.JSON).extract().response();
}

Related

Bad request with RestTemplate -> postForObject (Spring Boot)

I'm experiencing some troubles with a simple matter.
I'm trying to send a request to other REST service
//getting restTemplate from RestTemplateBuilder.build()
//endpoint and rest of variables came in properties
Map<String, String> map = new HashMap<>();
map.put("app", app);
map.put("username", username);
map.put("password", password);
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
String token = restTemplate.postForObject(loginEndpoint, headers, String.class, map);
And I recive:
Unexpected error occurred in scheduled task.
org.springframework.web.client.HttpClientErrorException: 400 Bad Request
The weird thing, when I use a simple CURL call and works smooth.
Already checked the variables and endpoint, and it's correct.
In this case, endpoint must have appropiate placeholders on end point url.
I made this method to do it easy:
private String placeHolders(Map<String, String> values){
String response = "?";
boolean first = true;
for(Map.Entry<String, String> entry:values.entrySet()){
if(first){
first = false;
}else{
response+="&";
}
response+=entry.getKey()+"="+entry.getValue();
}
return response;
}
And the call now Is:
String token = restTemplate.postForObject(loginEndpoint+placeHolders, headers, String.class, map);

How to POST array of strings with Java 11 HttpClient?

Trying to call an interface which accepts two POST parameters:
param1: string
param2: Array[string]
My attempt to post Array<String> as just a String is obviously naive, but can't find a better way. What would be the right way to post a parameter with the array of strings using Java 11 native HttpClient?
public static HttpResponse<String> postRequest() throws IOException, InterruptedException {
HttpClient httpClient = HttpClientSingleton.getInstance();
Map<Object, Object> data = new HashMap<>();
data.put("param1", "val1");
data.put("param2", "[val21, val22, val23]");
HttpRequest request = HttpRequest.newBuilder()
.POST(ofFormData(data))
.uri(URI.create("http://localhost:19990/test"))
.build();
return httpClient.send(request, HttpResponse.BodyHandlers.ofString());
}
public static HttpRequest.BodyPublisher ofFormData(Map<Object, Object> data) {
var builder = new StringBuilder();
for (Map.Entry<Object, Object> entry : data.entrySet()) {
if (builder.length() > 0) {
builder.append("&");
}
builder.append(URLEncoder.encode(entry.getKey().toString(), StandardCharsets.UTF_8));
builder.append("=");
builder.append(URLEncoder.encode(entry.getValue().toString(), StandardCharsets.UTF_8));
}
return HttpRequest.BodyPublishers.ofString(builder.toString());
}
Easier way could be, encode all the values as json, and parse (decode ) once you receive data in the server side. Cheers!

How to iteratively create Pact files in pact jvm

So I have a json file that has some request and response data, and what I want to accomplish is iterate through this data and create a pact file that uses each request and response.
So at the moment I am using a parameterized test in junit to kinda iterate through our json data, and this basically works except for because the producer name is the same for all pacts, it creates the same file and is overwriting the previous.
private JsonObject requestObject;
private static Gson gson = new Gson();
private static File jsonFile = readJsonFile();
private static int randValue = new Random().nextInt(500);
private static String consmerName = "phx-ev-consumer" + randValue;
#Rule
public PactProviderRuleMk2 provider = new PactProviderRuleMk2("phx-ev-svc-provider", "localhost", 8080, this);
final RestTemplate restTemplate = new RestTemplate();
public EligibilityApiConsumerPactTest(JsonObject requestObject) {
this.requestObject = requestObject;
}
#Parameterized.Parameters
public static Collection primeNumbers() throws JsonSyntaxException, JsonIOException, FileNotFoundException {
return getJson();
}
#Pact(state = "provider accets submit contact form", provider = "phx-ev-svc-provider" , consumer = "phx-ev-consumer")
public RequestResponsePact createFragment(PactDslWithProvider builder) {
Map<String, String> requestHeaders = new HashMap<>();
requestHeaders.put("Content-Type", "application/json");
requestHeaders.put("SM_USER", "wtadmin");
requestHeaders.put("Cookie", "SMCHALLENGE=YES");
// Auth headers
String authString = "wtadmin:labcorp1";
String authEncoded = Base64.getEncoder().encodeToString(authString.getBytes());
requestHeaders.put("Authorization", "Basic " + authEncoded);
Map<String, String> responseHeaders = new HashMap<>();
responseHeaders.put("Content-Type", "application/json");
String jsonRequest = requestObject.get("request").toString();
String jsonResponse = requestObject.get("response").toString();
RequestResponsePact pact = builder.given("phx-eligibility").uponReceiving("Phoenix Eligibility Request")
.method("POST").headers(requestHeaders).body(jsonRequest).path("/phx-rest/eligibility")
.willRespondWith().status(200).headers(responseHeaders).body(jsonResponse).toPact();
return pact;
}
#Test
#PactVerification("phx-ev-svc-provider")
public void runTest() throws IOException {
MultiValueMap<String, String> requestHeaders = new LinkedMultiValueMap<>();
requestHeaders.add("Content-Type", "application/json");
requestHeaders.add("SM_USER", "wtadmin");
requestHeaders.add("Cookie", "SMCHALLENGE=YES");
// Auth headers
String authString = "wtadmin:labcorp1";
String authEncoded = Base64.getEncoder().encodeToString(authString.getBytes());
requestHeaders.add("Authorization", "Basic " + authEncoded);
String jsonRequest = requestObject.get("request").toString();
restTemplate.exchange(provider.getConfig().url() + "/phx-rest/eligibility", HttpMethod.POST,
new HttpEntity<>(jsonRequest, requestHeaders), String.class);
}
public static List<JsonObject> getJson() throws JsonSyntaxException, JsonIOException, FileNotFoundException {
List<JsonObject> results = new ArrayList<JsonObject>();
JsonObject jsonObject = gson.fromJson(new FileReader(jsonFile), JsonObject.class);
JsonArray input = jsonObject.getAsJsonArray("input");
Iterator<JsonElement> iter = input.iterator();
while (iter.hasNext()) {
JsonObject obj = (JsonObject) iter.next();
results.add(obj);
}
return results;
}
public static File readJsonFile() {
File base = new File("");
File inputFile = new File(base.getAbsolutePath() + "/pact/input/eligibility.json");
return inputFile;
}
Not sure if there is a better way to accomplish this, I have looked at the Github for Pact Jvm and looked through stack overflow but have not been able to find someone creating pact files, without statically specifying all of the data.
A Pact file is essentially a JSON document that contains details about a consumer, a provider and a list of interactions. In your case, you seems to have the same consumer and provider, but a JSON file with the requests and responses that make up the interactions.
So you need to create a single pact file, but with an interaction added for each item in your JSON file.
There are a number of ways you can do that, but if you modify your example test, you can chain the calls using the DSL builder by calling .uponReceiving again after the last .body. You can do this in a loop, each additional call to .uponReceiving will start adding a new interaction to the pact. You will have to give each interaction a unique description.
Then call .toPact() at the end to create the final pact.

How to pass array of variables to REST URL in android?

I have to make registration using REST URL. REST services are written in Java now i have to pass the set of parameters in that secGameIds parameter is like this [100,102]. Example registration using Insomnia:::
{
"firstName":"parent111",
"lastName":"sadfsdf",
"email":"abc#bbc.com",
"date":"2000-06-09",
"phoneNum":"8765654454",
"gender":"male",
**"secGameIds":[0,0],**
"roleId":102
}
How should i provide secGameIds parameter value is it a ArrayList or Array?
for remaining values i have created JSONObject class object and adding values to that object and 'm appending that object to url
{
JSONObject json = new JSONObject();
json.put("fistName","aaa");
..
..
HttpPost post = new HttpPost(uri);
post.setHeader("Content-type", "application/json");
post.setEntity(new StringEntity(json.toString(), "UTF-8"));
DefaultHttpClient client = new DefaultHttpClient();
httpresponse = client.execute(post);
}
where as for secGameId i have tried like below,
{
int[] secGameId = {100,102};
}
-- gives me an error in back-end like "nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of int[] out of VALUE_NUMBER_INT token"
I even tried by using
{
ArrayList<Integer> secGameId = new ArrayList<String>();
secGameId.add(100);
secGameId.add(102);
}
and passing to value...
{
json.put("secGameIds":secGameId)
}
again at server side i kicked with the same error.
Can anyone help me?
public static String httpPost(HashMap<String, String> map, String url,String token) {
Log.e("call ", "running");
HttpRequest request;
if(token!=null){
request = HttpRequest.post(url).accept("application/json")
.header("Authorization", "Token " + AppInfo.token).form(map);
}
else
request = HttpRequest.post(url).accept("application/json").form(map);
int responseCode = request.code();
String text = request.body();
Log.e("response", " "+responseCode+ " "+ text);
if(responseCode==400){
return "invalid_tocken";
}
else if(responseCode<200 || responseCode>=300) {
return "error";
}
return text;
}
Hope you can convert the JSONArray to HashMap. If you instead need to post it as a JSONArray itself, then OkHttp library will help you.

aquery post with no hashmap like in Qt

I am porting an app from BB10 to android. For an http request I am using AQuery.
In Qt on BB10, I can simply post data:
QByteArray data = "test";
QNetworkRequest request;
request.setUrl(new QUrl("example.com"));
QNetworkAccessManager manager = new QNetworkAccessManager(this);
manager->post(request,data);
but in AQuery I can only find a POST method with key/value pairs (from the doc):
String url = "http://search.twitter.com/search.json";
Map<String, Object> params = new HashMap<String, Object>();
params.put("q", "androidquery");
aq.ajax(url, params, JSONObject.class, new AjaxCallback<JSONObject>() {
#Override
public void callback(String url, JSONObject json, AjaxStatus status) {
showResult(json);
}
});
Is there a way to POST just data in AQuery?
I have found out how to do this.
In the AQuery source, in the httpEntity method of the AbstractAjaxCallback class:
HttpEntity entity = null;
Object value = params.get(AQuery.POST_ENTITY);
if(value instanceof HttpEntity){
entity = (HttpEntity) value;
} else {
//urlencoded POST data
}
So all I needed to do was this:
HttpEntity entity = new StringEntity(data);
cb.param(AQuery.POST_ENTITY,entity);
where cb is my AjaxCallback object.

Categories

Resources