cancel
Showing results for 
Search instead for 
Did you mean: 
cancel
Showing results for 
Search instead for 
Did you mean: 

Using REST API with java to invoke service with parameters

SOLVED
Highlighted
Newbie

Using REST API with java to invoke service with parameters

Hi,

I currently try to use a POST request to send json data to a service on the TWX platform.

I successed to invoke the service, i can see it in the script log.

The thing invoked take 2 optionnal inputs :

  • value a TEXT, just to test the send...
  • jsonObj is the JSON object i want to send, to process it after

But here is the problem : both of these inputs stay at ​undefined​ state, and i didn't manage to get the data....

Here is the Java code used to send the request :

HttpsURLConnection conn =

  (HttpsURLConnection) url.openConnection();

byte[] postData = jsonData.getBytes(StandardCharsets.UTF_8);
int postDataLength = postData.length;
conn.setRequestMethod("POST");
conn.setRequestProperty("x-thingworx-session", "true");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty( "Content-Length", Integer.toString( postDataLength ));
conn.setRequestProperty("appKey", appKey);
// Create the form content
conn.setDoOutput(true);
DataOutputStream out = new DataOutputStream(conn.getOutputStream());
out.write(postData);
out.flush();
out.close();
if (conn.getResponseCode() != 200) {

   throw new IOException(conn.getResponseMessage());
}


Can comeone help me to understand why my jsonObj is still undefined ? The JsonData is a String got from a JSONObject.


Thanks,

Kevin B.

Tags (2)
1 ACCEPTED SOLUTION

Accepted Solutions
Highlighted

Re: Using REST API with java to invoke service with parameters

Kevin, I'm not sure if you did this already, but please do take a look at this knowledgebase article link on how to post json content to a service.

View solution in original post

2 REPLIES 2
Highlighted

Re: Using REST API with java to invoke service with parameters

Kevin, I'm not sure if you did this already, but please do take a look at this knowledgebase article link on how to post json content to a service.

View solution in original post

Highlighted

Re: Using REST API with java to invoke service with parameters

Thanks, is didn't found this article before.

I tryed so to build my string manually :

int id = 0;
String str="";
str+="{\"jsonObj\":\"{\"jsonObj\":{"; // Let's append now propertyName : pName, propertyValue : pValue;
for(String s : data){

  str+="\"PropertyName\":\"S"+id+"\",\"PropertyValue\":\""+s+"\"";
  id++;
  if(id != data.size()){

  str+=",";
  }

}

str+="}}\"}";


But it still did'nt work. The article does not specify how to feed the body in Java, maybe I did an error during the feeding of the REST call body ?

The String containing my data looks good

Announcements

Thingworx Navigate content has a new home! Click here to access the new Thingworx Navigate forum!