how to send request payload in json data using post method - java

String pay= "["
+ "{"
+ "\"internalAssessmentResponseId\" : \"Mer\\/ccclsv__AC1B752E-D079-4BA9-AA4F-46E1F8DDC11F__3048\","
+ "\"responses\":["
+ "{"
+ "\"assessmentCreatedDate\":\"2016-11-25T11:35:54\","
+ "\"responseData\":[],"
+ "\"assessmentId\":\"943\","
+ "}"
+ "],"
+ "\"addtionalInformation\":[],"
+ "\"emailId\":\"lucky#me.com\","
+ "\"salesTeam\" :\"\","
+ "\"demographic\": {"
+ "},"
+ "\"repId\":\"AJMA-OG9OMQ\","
+ "\"assesseeId\":\"AGHA-2D0FVL\","
+ "\"assesseeType\":\"CONTACT\","
+ "\"typeOfResponse\":\"iPad\","
+ "\"userTimeZone\":\"a\""
+ "}"
+ "]";
HttpClient httpclient = new HttpClient();
PostMethod post = new PostMethod("http://signature");
post.setRequestEntity(new StringRequestEntity(pay, "application/json", null));
httpclient.executeMethod(post);
String jsonResponse = post.getResponseBodyAsString();
jsonInsertRes = jsonResponse;
System.out.println("Response in create==>"+jsonResponse);
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch
(IOException e)
{
e.printStackTrace();
}
return jsonString.toString();
}
I am getting wrong response like this
Can not construct instance of org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput, problem: abstract types can only be instantiated with additional type information
at [Source: org.apache.catalina.connector.CoyoteInputStream#11ff00b3; line: 1, column: 1]

You can try sending JSON string as a string form parameter
and then on server read the JSON string value and convert the string to a Java Object(say object of Message.java as for example).
Message msgFromJSON = new ObjectMapper().readValue(JSONString, Message.class);
I have tried few times and it worked fine.

Related

Why -from Java- JSON returns this error? Clearly is in the JSON deserialization, but I cannot find exactly where it occurs

Situation:
[![from Postman, JSON returns the data correctly][1]][1]
[1]: https://i.stack.imgur.com/4Kk0J.png
Server side:
Enables the reading of the request body for all routes under /api/articulos.
Router router = Router.router(vertx);
router.route("/api/articulos*").handler(BodyHandler.create());
router.get("/api/articulos/:cantcomp1/:cantcomp2/:tipoprod/:prodpadre").handler(bizArticulo::getOneReadingBarcode);
Business
private static final String SELECT_CBA = "select art.leyenda, $1 :: numeric as cantidad, uni.abreviatura, "
+ "round(((art.precio_costo * (art.utilidad_fraccionado/100)) + art.precio_costo) * ($2),2) as totpagar "
+ "FROM public.articulos art join public.unidades uni on uni.idunidad = art.idunidad "
+ "WHERE (substring(art.codigobarra,1,2) = ($3) and substring(art.codigobarra,3,6) = ($4))";
public void getOneReadingBarcode(RoutingContext routingContext) {
Double cantComprada1 = Double.parseDouble(routingContext.request().getParam("cantcomp1"));
Double cantComprada2 = Double.parseDouble(routingContext.request().getParam("cantcomp2"));
String tipoProducto = routingContext.request().getParam("tipoprod");
String productoPadre = routingContext.request().getParam("prodpadre");
HttpServerResponse response = routingContext.response();
pgClient
.preparedQuery(SELECT_CBA)
.execute(Tuple.of(cantComprada1, cantComprada2, tipoProducto, productoPadre), ar -> {
if (ar.succeeded()) {
RowSet<Row> rows = ar.result(); // return always ONE ARTICLE
List<Articulo> articulos = new ArrayList<>();
rows.forEach(row -> {
articulos.add(fromBarCode(row));
});
response.putHeader("content-type", "application/json; charset=utf-8")
.setStatusCode(200)
.end(Json.encodePrettily(articulos));
} else {
System.out.println("Failure: " + ar.cause().getMessage());
response.putHeader("content-type", "application/json; charset=utf-8")
.end(Json.encodePrettily(ar.cause().getMessage()));
}
});
}
private static Articulo fromBarCode(Row row) {
String leyenda = row.getString("leyenda");
BigDecimal cantComprada = row.getBigDecimal("cantidad");
String abreviatura = row.getString("abreviatura");
BigDecimal total_a_pagar = row.getBigDecimal("totpagar");
Articulo articulo = new Articulo();
articulo.setLeyenda(leyenda);
articulo.setCant_comprada(cantComprada);
articulo.setAbreviatura(abreviatura);
articulo.setTot_a_pagar(total_a_pagar);
return articulo;
}
Client-side
private void validarArticulo() {
switch (txtCodigoBarra.getText().substring(0,2)) {
case "20":
Integer d = Integer.parseInt(txtCodigoBarra.getText().substring(8, 12));
Double decimal = d * 0.001; // convert to kilos
System.out.println(
String.format("%.3f", decimal) + " | " +
String.format("%.3f", decimal) + " | " +
txtCodigoBarra.getText().substring(0, 2) + " | " +
txtCodigoBarra.getText().substring(2, 8)
);
PosAccess
.getCodigoBarra(
decimal,
decimal,
txtCodigoBarra.getText().substring(0, 2),
txtCodigoBarra.getText().substring(2, 8));
case "77":
}
public static ObservableList<Articulo> getCodigoBarra(Double cantComp1, Double cantComp2, String tipoProducto, String productoPadre) {
ObservableList<Articulo> itemsArticulo = FXCollections.observableArrayList();
WebClient client = WebClient.create(Vertx.vertx());
client
.get(PORT, HOST, "/api/conceptos/" + cantComp1 + "/" + cantComp2 + "/" + tipoProducto + "/" + productoPadre)
// .get(PORT, HOST, "/api/conceptos/")
// .setQueryParam("cantcomp1", cantComp1)
// .addQueryParam("cantcomp2", cantComp2)
// .addQueryParam("tipoproducto", tipoProducto)
// .addQueryParam("productopadre", productoPadre)
.send(ar -> {
if (ar.succeeded()) {
HttpResponse<Buffer> response = ar.result();
response.bodyAsJsonArray().forEach(articulo -> {
JsonObject jo = (JsonObject) articulo;
itemsArticulo.add(new Articulo(jo.getString("leyenda"), jo.getDouble("cant_comprada"), jo.getString("abreviatura"), jo.getDouble("tot_a_pagar")));
});
System.out.println("Received response with status code " + response.statusCode());
System.out.println(response.bodyAsJsonArray());
} else {
System.out.println("Something went wrong " + ar.cause().getMessage());
}
});
return itemsArticulo;
}
Ok, that's the code. When scan the barcode I get this error
0,750 | 0,750 | 20 | 021162
oct. 11, 2020 6:33:18 A. M. io.vertx.core.impl.ContextImpl
SEVERE: Unhandled exception
io.vertx.core.json.DecodeException: Failed to decode:Unexpected character ('<' (code 60)): expected a valid value (JSON String, Number, Array, Object or token 'null', 'true' or 'false')
at [Source: (io.netty.buffer.ByteBufInputStream); line: 1, column: 2]
at io.vertx.core.json.jackson.JacksonCodec.fromParser(JacksonCodec.java:100)
at io.vertx.core.json.jackson.JacksonCodec.fromBuffer(JacksonCodec.java:67)
at io.vertx.ext.web.codec.impl.BodyCodecImpl.lambda$static$2(BodyCodecImpl.java:51)
at io.vertx.ext.web.client.impl.HttpResponseImpl.bodyAsJsonArray(HttpResponseImpl.java:116)
at consumer.PosAccess.lambda$0(PosAccess.java:45)
at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
at java.base/java.lang.Thread.run(Thread.java:834)
Caused by: com.fasterxml.jackson.core.JsonParseException: Unexpected character ('<' (code 60)): expected a valid value (JSON String, Number, Array, Object or token 'null', 'true' or 'false')
at [Source: (io.netty.buffer.ByteBufInputStream); line: 1, column: 2]
... 22 more
Anyboy can help me?
TIA
Ernesto
You are calling the wrong endpoint (i.e. /api/conceptos/ instead of /api/articulos).
In the screenshot provided in the post, which illustrates a correct response, you are showing a response for url
192.168.0.15:8092/api/articulos/0.75/0.75/20/021162
but in the code you have
client.get(PORT, HOST, "/api/conceptos/" + cantComp1 + "/" + cantComp2 + "/" + tipoProducto + "/" + productoPadre)
According to my experiences, this error message:
io.vertx.core.json.DecodeException: Failed to decode:Unexpected character ('<'
usualy happens when you try to deserialize an api response into a json, but indeed the response is something like:
<html><body><h1>Resource not found</h1></body></html>
or
<html><body><h1>Internal server error</h1></body></html>
and the parsing fails at the first char <
For your case, this happens at response.bodyAsJsonArray() probably.
please make a debug output for the url what you are calling:
String url = "/api/conceptos/" + cantComp1 + "/" + cantComp2 + "/" + tipoProducto + "/" + productoPadre;

Webview Send Post Json

I have String Json:
String data = "param:"+"{\"dataFile\": \n" +
"{\"user\": \"asdasdasd\", \n" +
"\"pwd\":\"vasdadsda\", \"email\": \"vasdasdasd#gg.com\" \n" +
"}\n" +
"}";
Then try to send post to API with webview JSON like this:
myWebView.postUrl("url.com", data.getBytes());
from API the json process with "param" key then get the value, but the json get from API is null, any clue ?
I post my data like this. You may also try with this.
String postData = null;
try {
postData = "email=" + URLEncoder.encode(MyApp.getSharedPrefString(StaticData.EMAIL), "UTF-8") + "&password=" + URLEncoder.encode(MyApp.getSharedPrefString(StaticData.PASSWORD), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
webview.postUrl("url.com",postData.getBytes());

Parsing Merriam Webster JSON data attributes wrapped in a double array?

I am attempting to get the definition of a word using the documentation from Merriam Webster's API - https://dictionaryapi.com/products/json#sec-2.def
The documentation shows the structure of the JSON response from the server, and I have been able to successfully parse the raw data into a just an array containing the "sense" object.
Screenshot of code and parsed data
My issue is being able to access the "sense" JSONObject, since I am currently in an array, I can't access the sense object. I have tried adding .getJSONArray(0) and .getJSONObject(0) after my code and both of those solutions did not work.
How can I continue parsing this JSON I currently have to the "dt" string?
JSONArray merriamResults = data.getJSONArray("Merriam")
.getJSONObject(0)
.getJSONArray("def")
.getJSONObject(0)
.getJSONArray("sseq")
.getJSONArray(0)
.getJSONArray(0);
Here.
String json = "{\"def\":[\n" +
" {\n" +
" \"sseq\":[\n" +
" [\n" +
" [\n" +
" \"sense\",\n" +
" {\n" +
" \"dt\":[[\"text\",\"{bc}a {a_link|backward} somersault especially\n" +
" in the air\"]]\n" +
" }\n" +
" ]\n" +
" ]\n" +
" ]\n" +
" }\n" +
"]}";
try {
JSONObject jsonObject = new JSONObject(json);
String dt = jsonObject.getJSONArray("def")
.getJSONObject(0)
.getJSONArray("sseq")
.getJSONArray(0)
.getJSONArray(0)
.getJSONObject(1)
.getJSONArray("dt")
.getJSONArray(0)
.getString(1);
Log.i("jsondata", dt);
} catch (JSONException e) {
e.printStackTrace();
}
my log:
12-02 21:38:12.316 14174-14174/com.example.pemba.sample I/jsondata: {bc}a {a_link|backward} somersault especially
in the air

URL in JSON object as POST request Android

Please help me to send a JSON object in POST HTTP request through HttpClient, in Android.
The problem I am facing is that the JSON object having the URL is replaced by forward slash ,i.e
originally it should have the following value in JSON object
{"product":
{"featured_src":"https:\/\/example.com\/wp-content\/uploads\/2015\/06\/sidney-compressed.jpg,
"short_description":"this is a test","title":"Raiders from the North"}
}
i tried many options to keep it in the above format. But it always comes as {"featured_src":
We assume this is your input
private final static String JSON_DATA = "{"
+ " \"product\": ["
+ " {"
+ " \"featured_src\": \"https:\\/\\/example.com\\/wp-content"
+ "\\/uploads\\/2015\\/06\\/sidney-compressed.jpg\","
+ " \"short_description\": \"this is a test\","
+ " \"title\" : \"Raiders from the North\""
+ " }"
+ " ]"
+ "}";
You could use replace to do the trick.
YOUR_STRING.replace("\\", "");
Finally your method would look like this, by passing your string as parameter
private static String jsonUrlCorrector(String json_data) {
json_data = json_data.replace("\\", "");
return json_data;
}
Here is the input:
{"product":[{"featured_src":"https:\/\/example.com\/wp-content\/uploads\/2015\/06\/sidney-compressed.jpg","short_description": "this is a test","title":"Raiders from the North"}]}
Here is the output
{"product":[{"featured_src":"https://example.com/wp-content/uploads/2015/06/sidney-compressed.jpg","short_description":"this is a test","title":"Raiders from the North"}]}

Google custom search engine android not accepting %20 or white space

EDIT 2
Found my error i was passing invalid an invalid parameter just remebered i was tryiong out stuff.
Sorry For the Trouble GUYS
I am using Google custom search engine for the first time and so far every thing is fine. However, when i try to send a query for an item which has a white space the search engine returns a bad request response eg
myUrl = (CustomSearchEngineURL + API_KEY + "&cx=" + cxKey + "&q="
+ q.replace(" ", "%20") + "&searchType=" + searchType
+ "&imgType=" + imgType + "&imgSize=" + imgSize + "&num=20&alt=json");
This returns this
com.google.api.client.http.HttpResponseException: 400 Bad Request
EDIT
i took the advice of 323go and tried encoding my q and this is how i implemented it
String encodedParms = null;
try {
encodedParms = URLEncoder.encode(q, "UTF-8");
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
myUrl = (CustomSearchEngineURL + API_KEY + "&cx=" + cxKey + "&q="
+ encodedParms + "&searchType=" + searchType + "&imgType="
+ imgType + "&imgSize=" + imgSize + "&num=20&alt=json");
Log.d(Tag, myUrl);
HttpRequestFactory httpRequestFactory = createRequestFactory(HTTP_TRANSPORT);
HttpRequest request;
try {
request = httpRequestFactory.buildGetRequest(new GenericUrl(myUrl));
String response = streamToString(request.execute().getContent());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
In my log i got this as the url
https://www.googleapis.com/customsearch/v1?key=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-w&cx=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&q=Sunway+Lagoon+Theme+Park&searchType=image&imgType=photo&imgSize=xxlarge&num=20&alt=json
i still got the same bad request error
please can anyone tell me what i am doing worng
Why dont you add "+" between words, I had same issue
With "word1 word2" - response 400 - Bad request
With "word1+word2" - response 2000 - Bad request

Categories