WP Rest API - Post to ACF field? - java

I'm trying to post to my custom Wordpress field via the REST API from my android app. That said, when I look at the JSON structure of any ACF fields, they're nested inside "acf" like so:
{
"acf": {
"phone_number": "000-0000"
}
}
I'm trying to post a phone number to the phone_number field at my endpoint with the following code/structure, but it won't seem to save?
OkHttpClient client = new OkHttpClient();
String url = "http://myurl.com/wp-json/wp/v2/users/loggedinuser/36";
String bearer = "Bearer ";
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("phone_number", "777-348-4349");
} catch (JSONException e) {
e.printStackTrace();
}
RequestBody body = RequestBody.create(JSON, jsonObject.toString());
Request request = new Request.Builder()
.url(mergeUrl)
.method("POST", body)
.addHeader("Accept-Charset", "application/json")
.addHeader("Authorization", bearer + userToken)
.addHeader("Content-Type", "application/json")
.build();
Response response = null;
try {
response = client.newCall(request).execute();
String resStr = response.body().string();
int responseCode = response.code();
if (responseCode == 200) {
} else {
}
} catch (IOException | JSONException e) {
e.printStackTrace();
}
return null;
}}
I imagine it's because phone_number is nested inside of "acf". How can I write this line:
jsonObject.put("phone_number", "777-348-4349");
so that it matches the structure above? I can't seem to figure out how to nest phone_number inside of the acf value.

Here's how you can nest it to match the structure:
JSONObject jsonObject = new JSONObject();
try {
JSONObject acf = new JSONObject();
acf.put("phone_number", "777-348-4349");
jsonObject.put("acf", acf);
} catch (JSONException e) {
e.printStackTrace();
}
let me know if this worked for you.

Using ACF with the REST API is explained on this page. To sum it up:
You need at least ACF version 5.11
You need to enable the REST API for your field groups
The endpoints for users are /users/{user_id} and /users/me (not /users/loggedinuser/{user_id})
The JSON structure is the following:
{
"acf":
{
"field": "Value"
}
}

Related

Split nested json data

I am trying to split nested json data
private String TickData(String token) {
OkHttpClient client = new OkHttpClient().newBuilder().build();
Request request = new Request.Builder()
.url("https://history.truedata.in/getticks?symbol=NIFTY 50&from=211201T09:15:00&to=211201T15:30:00&response=json&bidask=1")
.method("GET", null)
.addHeader("Authorization", "Bearer " + token)
.build();
try {
Response response = client.newCall(request).execute();
Log.d(TAG, "TickData: tick data response: " + response.body().string());
String s = response.body().string();
Log.e(TAG, "TickData: s: " + s );
} catch (Exception e) {
e.printStackTrace();
}
return tickdata;
}
this is my nested json data.
{"status":"Success","Records":[["2021-12-01T09:15:00",17104.4,0,0,0.0,0,0.0,0],["2021-12-01T09:15:00",17105.05,0,0,0.0,0,0.0,0],["2021-12-01T09:15:00",17082.0,0,0,0.0,0,0.0,0],["2021-12-01T09:15:00",17082.0,0,0,0.0,0,0.0,0],["2021-12-01T09:15:01",17079.75,0,0,0.0,0,0.0,0],["2021-12-01T09:15:01",17085.1,0,0,0.0,0,0.0,0],["2021-12-01T09:15:02",17088.65,0,0,0.0,0,0.0,0],["2021-12-01T09:15:03",17090.7,0,0,0.0,0,0.0,0],["2021-12-01T09:15:04",17095.3,0,0,0.0,0,0.0,0],["2021-12-01T09:15:05",17099.4,0,0,0.0,0,0.0,0],["2021-12-01T09:15:06",17106.05,0,0,0.0,0,0.0,0],["2021-12-01T09:15:06",17105.75,0,0,0.0,0,0.0,0],["2021-12-01T09:15:07",17109.0,0,0,0.0,0,0.0,0],["2021-12-01T09:15:07",17107.1,0,0,0.0,0,0.0,0],["2021-12-01T09:15:08",17110.85,0,0,0.0,0,0.0,0],["2021-12-01T09:15:08",17110.55,0,0,0.0,0,0.0,0],["2021-12-01T09:15:09",17120.9,0,0,0.0,0,0.0,0],["2021-12-01T09:15:09",17119.4,0,0,0.0,0,0.0,0],["2021-12-01T09:15:10",17125.9,0,0,0.0,0,0.0,0],["2021-12-01T09:15:10",17125.9,0,0,0.0,0,0.0,0],["2021-12-01T09:15:11",17128.3,0,0,0.0,0,0.0,0],["2021-12-01T09:15:11",17126.75,0,0,0.0,0,0.0,0],["2021-12-01T09:15:12",17130.45,0,0,0.0,0,0.0,0],["2021-12-01T09:15:12",17129.25,0,0,0.0,0,0.0,0],["2021-12-01T09:15:13",17131.55,0,0,0.0,0,0.0,0],["2021-12-01T09:15:13",17131.4,0,0,0.0,0,0.0,0],["2021-12-01T09:15:14",17134.85,0,0,0.0,0,0.0,0],["2021-12-01T09:15:14",17133.25,0,0,0.0,0,0.0,0],["2021-12-01T09:15:15",17136.65,0,0,0.0,0,0.0,0],["2021-12-01T09:15:15",17135.7,0,0,0.0,0,0.0,0],["2021-12-01T09:15:16",17137.35,0,0,0.0,0,0.0,0],["2021-12-01T09:15:16",17134.85,0,0,0.0,0,0.0,0],["2021-12-01T09:15:17",17135.95,0,0,0.0,0,0.0,0],["2021-12-01T09:15:19",17138.45,0,0,0.0,0,0.0,0],["2021-12-01T09:15:19",17136.0,0,0,0.0,0,0.0,0],["2021-12-01T09:15:20",17140.4,0,0,0.0,0,0.0,0],["2021-12-01T09:15:20",17138.85,0,0,0.0,0,0.0,0],["2021-12-01T09:15:21",17142.8,0,0,0.0,0,0.0,0],["2021-12-01T09:15:21",17138.7,0,0,0.0,0,0.0,0],["2021-12-01T09:15:22",17145.6,0,0,0.0,0,0.0,0],["2021-12-01T09:15:22",17144.35,0,0,0.0,0,0.0,0],["2021-12-01T09:15:23",17147.25,0,0,0.0,0,0.0,0],["2021-12-01T09:15:23",17146.55,0,0,0.0,0,0.0,0],["2021-12-01T09:15:24",17149.6,0,0,0.0,0,0.0,0],["2021-12-01T09:15:24",17149.25,0,0,0.0,0,0.0,0],["2021-12-01T09:15:24",17150.35,0,0,0.0,0,0.0,0],["2021-12-01T09:15:24",17147.15,0,0,0.0,0,0.0,0],["2021-12-01T09:15:25",17147.15,0,0,0.0,0,0.0,0],["2021-12-01T09:15:26",17148.15,0,0,0.0,0,0.0,0],["2021-12-01T09:15:27",17144.65,0,0,0.0,0,0.0,0],["2021-12-01T09:15:28",17142.55,0,0,0.0,0,0.0,0],["2021-12-01T09:15:29",17135.3,0,0,0.0,0,0.0,0],["2021-12-01T09:15:30",17136.45,0,0,0.0,0,0.0,0],["2021-12-01T09:15:31",17134.65,0,0,0.0,0,0.0,0],["2021-12-01T09:15:32",17127.55,0,0,0.0,0,0.0,0],["2021-12-01T09:15:33",17127.3,0,0,0.0,0,0.0,0],["2021-12-01T09:15:34",17126.95,0,0,0.0,0,0.0,0],["2021-12-01T09:15:35",17128.2,0,0,0.0,0,0.0,0],["2021-12-01T09:15:36",17129.55,0,0,0.0,0,0.0,0],["2021-12-01T09:15:37",17130.4,0,0,0.0,0,0.0,0],["2021-12-01T09:15:38",17133.35,0,0,0.0,0,0.0,0],["2021-12-01T09:15:39",17134.2,0,0,0.0,0,0.0,0],["2021-12-01T09:15:40",17136.1,0,0,0.0,0,0.0,0],["2021-12-01T09:15:41",17137.55,0,0,0.0,0,0.0,0],["2021-12-01T09:15:42",17138.3,0,0,0.0,0,0.0,0],["2021-12-01T09:15:43",17145.05,0,0,0.0,0,0.0,0],["2021-12-01T09:15:44",17145.6,0,0,0.0,0,0.0,0],["2021-12-01T09:15:46",17146.3,0,0,0.0,0,0.0,0],["2021-12-01T09:15:47",17148.95,0,0,0.0,0,0.0,0],["2021-12-01T09:15:48",17151.95,0,0,0.0,0,0.0,0],["2021-12-01T09:15:48",17150.2,0,0,0.0,0,0.0,0],["2021-12-01T09:15:49",17152.55,0,0,0.0,0,0.0,0],["2021-12-01T09:15:49",17152.55,0,0,0.0,0,0.0,0],["2021-12-01T09:15:50",17154.35,0,0,0.0,0,0.0,0],["2021-12-01T09:15:50",17153.9,0,0,0.0,0,0.0,0],["2021-12-01T09:15:51",17155.4,0,0,0.0,0,0.0,0],["2021-12-01T09:15:51",17149.45,0,0,0.0,0,0.0,0],["2021-12-01T09:15:52",17157.35,0,0,0.0,0,0.0,0],["2021-12-01T09:15:52",17156.3,0,0,0.0,0,0.0,0],["2021-12-01T09:15:52",17158.3,0,0,0.0,0,0.0,0],["2021-12-01T09:15:52",17155.65,0,0,0.0,0,0.0,0],["2021-12-01T09:15:53",17157.7,0,0,0.0,0,0.0,0]]}
I have to split the record first after that collect all array data inside on it.
You can perhaps use Jackson api to parse it.
implementation 'com.fasterxml.jackson.core:jackson-databind:2.13.0'
then you can use following
String jsonString = "{\"status\":\"Success\",\"Records\":[[\"2021-12-01T09:15:00\",17104.4,0,0,0.0,0,0.0,0],[\"2021-12-01T09:15:00\",17105.05,0,0,0.0,0,0.0,0]]}";
ObjectMapper mapper = new ObjectMapper();
try {
Map map = mapper.readValue(jsonString, Map.class);
List<List> recordsList = (List<List>)map.get("Records");
// Now you can access the elements directly as following
System.out.println(recordsList.get(0).get(0));
} catch (JsonProcessingException e) {
e.printStackTrace();
}

How to call Json Post request with queryparam on client side?

I wrote both Service and CLient part of application. I tested my service with "Postman" application and it is working fine with url = http://192.168.2.50:8084/FaceBusinessService/webresources/service/login?phone=123456789&password=1234
However when I try to call it on my Android Application it is not working. While debuging on service side I see that phone and password parameters are NULL.
Here is my service side :
#Path("login")
#POST
#Produces("application/json")
public String postJson(#QueryParam("phone")String phone, #QueryParam("password") String password) {
String info = null;
try {
UserInfo userInfo = null;
UserModel userModel = new UserModel();
userInfo = userModel.isPersonRegistered(phone, password);
Gson gson = new Gson();
System.out.println(gson.toJson(userInfo));
info = gson.toJson(userInfo);
} catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
}
return info;
}
Here is my android app side :
private UserInfo loginUser(String phone, String password) {
UserInfo userInfo = null;
HttpClient httpClient = new DefaultHttpClient();
HttpPost post = new HttpPost("http://192.168.2.27:8084/FaceBusinessService/webresources/service/login");
try {
/*
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
entity.addPart("phone", new StringBody(phone));
entity.addPart("password", new StringBody(password));
post.setEntity(entity);
*/
List<NameValuePair> params = new ArrayList<NameValuePair>(2);
params.add(new BasicNameValuePair("phone", phone));
params.add(new BasicNameValuePair("password", password));
post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
Log.d(TAG, "POST String: " + post.toString());
try {
HttpResponse response = httpClient.execute(post);
if (response.getEntity().getContentLength() > 0) {
String json_string = EntityUtils.toString(response.getEntity());
JSONObject jsonObject = new JSONObject(json_string);
// TODO
return userInfo;
}
} catch (IOException e) {
e.printStackTrace();
return null;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
return null;
}
I tried both MultipartEntity and NameValuePair but none of them worked. Could you give me idea how to handle this issue?
Note that when testing with Postman you passed parameters (user name and password) as part of the URL (URL encoded), which can be directly retrieved on the server side. (you don't even need a POST request for this). Your objects are passed as string objects, not JSON objects.
In your client code , the URL is different because you're encoding the parameters as part of the POST request entity (payload). The parameters are packaged inside of the request/message body and not in the URL.
Now since your URL doesn't have the parameters, you should retrieve them by deserializing the request (desderialize the JSON request into a UserInfo object).
Note that you should rewrite your server side code completely as it should accept a application/JSON object but it apparently should return/produce a String object (plain/text or application/HTML).
I'm not familiar with GSON but your code might look something like
#Path("login")
#POST
#Produces("text/plain")
#Consumes("application/json")
public String postJson(UserInfo ui) {
String info = null;
try {
UserInfo userInfo = null;
UserModel userModel = new UserModel();
userInfo = userModel.isPersonRegistered(ui.phone, ui.password);
Gson gson = new Gson();
System.out.println(gson.toJson(userInfo));
info = gson.toJson(userInfo);
} catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
}
return info;
}

Retrieve response body from ClientResource

I try to issue a POST request with ClientResource, I'm able to retrieve the response STATUS, I also want to get the response body when I get an exception.
Here is my code:
public static Pair<Status, JSONObject> post(String url, JSONObject body) {
ClientResource clientResource = new ClientResource(url);
try {
Representation response = clientResource.post(new JsonRepresentation(body), MediaType.APPLICATION_JSON);
String responseBody = response.getText();
Status responseStatus = clientResource.getStatus();
return new ImmutablePair<>(responseStatus, new JSONObject(responseBody));
} catch (ResourceException e) {
logger.error("failed to issue a POST request. responseStatus=" + clientResource.getStatus().toString(), e);
//TODO - how do I get here the body of the response???
} catch (IOException |JSONException e) {
throw e;
} finally {
clientResource.release();
}
}
Here is the code that my server resource returns in case of failure
getResponse().setStatus(Status.CLIENT_ERROR_FORBIDDEN);
JsonRepresentation response = new JsonRepresentation( (new JSONObject()).
put("result", "failed to execute") );
return response;
I try to catch the "result" with no success
In fact, the getResponseEntity method returns the content of the response. It corresponds to a representation. You can wrap it by a JsonRepresentation class if you expect some JSON content:
try {
(...)
} catch(ResourceException ex) {
Representation responseRepresentation
= clientResource.getResponseEntity();
JsonRepresentation jsonRepr
= new JsonRepresentation(responseRepresentation);
JSONObject errors = jsonRepr.getJsonObject();
}
You can notice that Restlet also supports annotated exceptions.
Otherwise I wrote a blog post about this subject: http://restlet.com/blog/2015/12/21/exception-handling-with-restlet-framework/. I think that it could help you.
Thierry

How to send json from android to php?

To post json from android to php, i used Volley library StringRequest object.
StringRequest sr = new StringRequest(Request.Method.POST,url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
// some code
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//some code
}
}){
#Override
protected Map<String,String> getParams(){
Map<String, String> params = new HashMap<String, String>();
ArrayList<Command> commands = MyApplication.readFromPreferences(getActivity(), Constants.COMMAND);
String jsonCommands = new Gson().toJson(commands);
params.put("commands", jsonCommands);
return params;
}
};
And to catch the data in php and verify if it was sent correcttly, I used this
echo $_POST["commands"];
Output:
[{\"product\":{\"category_id\":1,\"created_at\":\"2015-06-13 17:49:58\",\"description\":\"CF77 COIN FINDER\",\"url_image\":\"IMG_76ECDC-707E7E-70AC81-0A1248-4675F3-F0F783.jpg\",\"name\":\"CF77 COIN FINDER\",\"pid\":12,\"price\":500.0},\"product_quantity\":3},{\"product\":{\"category_id\":1,\"created_at\":\"2015-06-13 17:49:58\",\"description\":\"JEOSONAR 3D DUAL SYSTEM\",\"url_image\":\"IMG_2D9DF0-2EB7E9-ED26C0-2C833B-B6A5C5-5C7C02.jpg\",\"name\":\"JEOSONAR 3D DUAL SYSTEM\",\"pid\":15,\"price\":500.0},\"product_quantity\":1},{\"product\":{\"category_id\":1,\"created_at\":\"2015-06-13 17:49:58\",\"description\":\"MAKRO POINTER\",\"url_image\":\"IMG_Macro.jpg\",\"name\":\"MAKRO POINTER\",\"pid\":18,\"price\":500.0},\"product_quantity\":3}]
I have noticed that when sending the json string with POST Method using Volley library, a lot of anti-slashes have been added to escape double quotes.
So here comes my problem:
I want to decode json to an array of objects in php, so i used
$commands = json_decode( $_POST["commands"],true);
But it always returns an empty array because of the invalide above json (caused by the anti-slashes).
Is there a method in php or in java SDK providing a contract for sending and receiving json without having this kind of problems? Or should i reformat the json in php and delete all the anti-slashes?
The problem is that you try to send the json data in the URL parameters.
You need to override the getBody() method to return the json data as request body, not as url parameters.
Eg:
/**
* Returns the raw POST or PUT body to be sent.
*
* #throws AuthFailureError in the event of auth failure
*/
public byte[] getBody() throws AuthFailureError {
return new Gson().toJson(commands).getBytes();
}
And then in PHP you can:
$jsonRequest = json_decode(stream_get_contents(STDIN));
first there is problem with the json itself is not build correctly is better to JSONObject for this, for example:
JSONObject js = new JSONObject();
try {
js.put("value",10);
} catch (JSONException e) {
e.printStackTrace();
}
String jss = js.toString();
you can check if the parse is success by copy the string and copy it in online parser like this http://json.parser.online.fr/
Finally, I solved my problem using a custom json_decode method in order to clean the json string before decoding it.
function json_clean_decode($json, $assoc = false, $depth = 512, $options = 0) {
// search and remove comments like /* */ and //
$json = preg_replace("#(/\*([^*]|[\r\n]|(\*+([^*/]|[\r\n])))*\*+/)|([\s\t]//.*)|(^//.*)#", '', $json);
// search and remove all backslashes
$json = str_replace("\\","", $json);
if(version_compare(phpversion(), '5.4.0', '>=')) {
$json = json_decode($json, $assoc, $depth, $options);
}
elseif(version_compare(phpversion(), '5.3.0', '>=')) {
$json = json_decode($json, $assoc, $depth);
}
else {
$json = json_decode($json, $assoc);
}
return $json;
}
You can use this method to send json to web service.
public String makeServiceCallSubmit(String url, int method,
JSONArray object) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-type", "application/json");
StringEntity se = new StringEntity(object.toString());
// se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httpPost.setEntity(se);
httpResponse = httpClient.execute(httpPost);
}
httpEntity = httpResponse.getEntity();
Response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return Response;
}

issue with Zen desk Api name User: Name: is too short (minimum one character)

When i tried to hit the zen desk api called user with a json request,it hits API successfully but getting an error Name: is too short (minimum one character)
I logged the request,and tested this request with a POSTER tool that time i was successfull in my attempt account got created in zend side
but when i tried the same with java code getting the above error,So help me in this issue
The logged request is
{
"user":
{
"name":"TEST CASE2",
"email":"case22#gmail.com",
"external_id":"5335356",
"role":"end-user",
"verified":"true"
}
}
And my code is
public static void createUser(String name, String email, String spAccountId,String verified) {
HttpClient c = new DefaultHttpClient();
String serviceUrl = "https://domain/api/v2/users.json";
HttpPost p = new HttpPost(serviceUrl);
p.setHeader("ContentType", "application/json");
p.setHeader("Accept", "application/json");
p.setHeader("Authorization","Basic tyytytreytytytreytytre=");
JsonObject jsonObjectRepresentation = Json.createObjectBuilder()
.add("user", Json.createObjectBuilder()
.add("name", name)
.add("email", email)
.add("external_id", spAccountId)
.add("role", "end-user")
.add("verified", verified).build()).build();
System.out.println(jsonObjectRepresentation.toString());
p.setEntity(new StringEntity(jsonObjectRepresentation.toString(), "UTF-8"));
HttpResponse r = c.execute(p);
JsonReader reader = Json.createReader(new InputStreamReader(r.getEntity().getContent()));
JsonObject jsonObject = reader.readObject();
reader.close();
System.out.println("jsonObject#######"+jsonObject);
}
out put from my java code
{"error":"RecordInvalid","description":"Record validation errors","details":{"name":[{"description":"Name: is too short (minimum one character)"}]}}
Out put From Poster tool:
{"user":{"id":502206130,"url":"https://domain.zendesk.com/api/v2/users/502206130.json","name":"TEST CASE3","email":"case3#me.com","created_at":"2014-07-17T08:12:04Z","updated_at":"2014-07-17T08:12:05Z","time_zone":"Hawaii","phone":null,"photo":null,"locale_id":16,"locale":"fr","organization_id":null,"role":"end-user","verified":true,"external_id":"434355","tags":[],"alias":null,"active":true,"shared":false,"shared_agent":false,"last_login_at":null,"signature":null,"details":null,"notes":null,"custom_role_id":null,"moderator":false,"ticket_restriction":"requested","only_private_comments":false,"restricted_agent":true,"suspended":false,"user_fields":{"abonnement_internet":null,"betapass":null,"box":null,"commune":null,"dcodeur_tns_tnt":null,"mac":null,"position_du_routeur":null,"routeur":null,"serial":null,"subscription":null}}}
I also had same problem, Solved using in header
"Content-Type" : "application/json"
I am not sure but I will suggest you one more way. Please use AsyncHttpClient instead of HttpClient
so I will format your code:
AsyncHttpClient client=new AsyncHttpClient();
JsonObject jsonObjectRepresentation = Json.createObjectBuilder()
.add("user", Json.createObjectBuilder()
.add("name", name)
.add("email", email)
.add("external_id", spAccountId)
.add("role", "end-user")
.add("verified", verified).build()).build();
Request request = client
.preparePost("https://niutv.zendesk.com/api/v2/users.json")
.setHeader("Content-Type","application/json")
.setHeader("Content-Length", "" + jsonObjectRepresentation.toString()
.length())
.setHeader("Authorization", "Basic b2pAbml1LXR2LmNvbTpnMGFRNzVDUnhzQ0ZleFQ=")
.setBody(jsonObjectRepresentation.toString()).build();
ListenableFuture<Response> r = null;
//ListenableFuture<Integer> f = null;
try {
r = client.executeRequest(request);
System.out.println(r.get().getResponseBody());
} catch(IOException e) {
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}

Categories

Resources