Skip to main content
14-Alexandrite
October 4, 2023
Solved

Rest api Java

  • October 4, 2023
  • 1 reply
  • 9395 views

I am calling rest api(thingworx url) from java eclipse but throwing error in java.Below is my code

 

String b64 = Base64.getEncoder().encodeToString(bytes);

//Construct jsoninput body//

JSONObject params=new JSONObject();

params.put("path","/Motivation.pdf");

params.put("content", b64);

 

//Load pdf to Thingworx repository//

String url = "HiddenServerurlforsafetypurpose/Thingworx/Things/komal_FileRepo/Services/SaveBinary";

 

URL obj = new URL(url);

 

HttpURLConnection con = (HttpURLConnection) obj.openConnection();

 

//add request header

 

con.setRequestMethod("POST");

 

con.setRequestProperty("Accept", "application/json");

 

con.setRequestProperty("Content-Type", "application/json");

 

con.setRequestProperty("appKey", "removedforsafetypurpose");

 

con.setRequestProperty("Body", params.toJSONString());

 

// Send post request

 

con.setDoOutput(true);

 

DataOutputStream wr = new DataOutputStream(con.getOutputStream());

 

wr.flush();

 

wr.close();

 

int responseCode = con.getResponseCode();

 

System.out.println("\nSending 'POST' request to URL : " + url);

 

System.out.println("Response Code : " + responseCode);

 

BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));

 

String inputLine;

 

StringBuilder response = new StringBuilder();

 

while((inputLine = in.readLine()) != null) {

 

response.append(inputLine);

 

}

 

in.close();

 

//print result

 

System.out.println(response.toString());

 

Error in Thingworx :

 

No Path Was Specified

 

[SECURITY FAILURE Anonymous:@unknown -> /ExampleApplication/IntrusionDetector] Invalid input: context=HTTP header value: body, type(HTTPHeaderValue)=^[a-zA-Z0-9()\-=\*\.\?;,+\/:&_ %$ ยก-￿'"]*$, input={"path":"\/Motivation.pdf","content":"JVBERi0xLjQKJeLjz9MKMiAwIG9iago8PC9MZW5ndGggMTIxL0ZpbHRlci9GbGF0ZURlY29kZT4+c3RyZWFtCnicFc3LCsIwEEbh\/TzF76oKXhKF0rVQQXfCvEAwE6uFjk1SxLc32Z3FB2emM9OpRWdasCeDne1qHC4W9ggOtL4G\/HRpokBDkCgeDklchk6loj5G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lUZXh0LTUuNS4xMy4yCnN0YXJ0eHJlZgo2NTkKJSVFT0YK"}

 

If i am passing same input to the service in thingworx directly,It is generating pdf.

 

Please help me how to pass json input

 

 

 

 

Best answer by KN_9954684

Thank you Velkumar for the much needed support.

1 reply

19-Tanzanite
October 5, 2023

Hi @KN_9954684 

 

I think there is some bug in the code. You are setting Body as POST Header Property.

 

Please refer to this one -

 

POSTing via a REST call in Java - PTC Community

 

Making a JSON POST Request With HttpURLConnection | Baeldung

 

/VR

14-Alexandrite
October 5, 2023

In the first example they are not setting body.

 

As per second example I set the body and changed the code but still I am getting error as "No path was specified"

 

Please check below code

 

String url = "Hiddenforsecuritypurpose/Things/komal_FileRepo/Services/SaveBinary";

 

String jsonInputString = "{"+"path"+":"+"/Motivation.pdf"+","+"content"+":"+b64+"}";

 

 

URL obj = new URL(url);

 

HttpURLConnection con = (HttpURLConnection) obj.openConnection();

 

//add request header

 

con.setRequestMethod("POST");

 

con.setRequestProperty("Accept", "application/json");

 

con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");

 

con.setRequestProperty("appKey", "Hidden");

 

//con.setRequestProperty("Body", jsonInputString);

 

 

// Send post request

 

con.setDoOutput(true);

 

// DataOutputStream wr = new DataOutputStream(con.getOutputStream());

//

// wr.flush();

//

// wr.close();

//

// int responseCode = con.getResponseCode();

//

// System.out.println("\nSending 'POST' request to URL : " + url);

//

// System.out.println("Response Code : " + responseCode);

//

// BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));

//

// String inputLine;

//

// StringBuilder response = new StringBuilder();

//

// while((inputLine = in.readLine()) != null) {

//

// response.append(inputLine);

//

// }

//

// in.close();

//

// //print result

//

// System.out.println(response.toString());

try(OutputStream os = con.getOutputStream()) {

byte[] input = jsonInputString.getBytes("utf-8");

os.write(input, 0, input.length);

}

try(BufferedReader br = new BufferedReader(

new InputStreamReader(con.getInputStream(), "utf-8"))) {

StringBuilder response = new StringBuilder();

String responseLine = null;

while ((responseLine = br.readLine()) != null) {

response.append(responseLine.trim());

}

System.out.println(response.toString());

}

19-Tanzanite
October 5, 2023

Hi @KN_9954684 

 

Please find below code 

 

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class restApiPostRequest {

	public static void main(String[] args) throws IOException {

		// Create URL Instance
		URL url = new URL("http://192.168.86.195:8080/Thingworx/Things/SystemRepository/Services/SaveBinary");

		// Open Connection
		HttpURLConnection conection = (HttpURLConnection) url.openConnection();
		// set HTTP Method
		conection.setRequestMethod("POST");

		// Set Headers to specify content types
		conection.setRequestProperty("Content-Type", "application/json");
		conection.setRequestProperty("Accept", "application/json");
 conection.setRequestProperty("appKey", "2d3571aa-8d70-40ad-b1be-2a32ebb69a1a");
		
		// to enable write content to request
		conection.setDoOutput(true);
		
		// making JSON String
		String jsonString = "{ \"content\": \"JVBERi0xLjQKJeLjz9MKMiAwIG9iago8PC9MZW5ndGggMTIxL0ZpbHRlci9GbGF0ZURlY29kZT4+c3RyZWFtCnicFc3LCsIwEEbh\\/TzF76oKXhKF0rVQQXfCvEAwE6uFjk1SxLc32Z3FB2emM9OpRWdasCeDne1qHC4W9ggOtL4G\\/HRpokBDkCgeDklchk6loj5GyUjD67OF16nJcGnEdyigqhVuS8p4SvX7Db\\/Lw9RDz3SnP8DJJHoKZW5kc3RyZWFtCmVuZG9iago0IDAgb2JqCjw8L1R5cGUvUGFnZS9NZWRpYUJveFswIDAgNTk1IDg0Ml0vUmVzb3VyY2VzPDwvRm9udDw8L0YxIDEgMCBSPj4+Pi9Db250ZW50cyAyIDAgUi9QYXJlbnQgMyAwIFI+PgplbmRvYmoKMSAwIG9iago8PC9UeXBlL0ZvbnQvU3VidHlwZS9UeXBlMS9CYXNlRm9udC9IZWx2ZXRpY2EvRW5jb2RpbmcvV2luQW5zaUVuY29kaW5nPj4KZW5kb2JqCjMgMCBvYmoKPDwvVHlwZS9QYWdlcy9Db3VudCAxL0tpZHNbNCAwIFJdPj4KZW5kb2JqCjUgMCBvYmoKPDwvVHlwZS9DYXRhbG9nL1BhZ2VzIDMgMCBSPj4KZW5kb2JqCjYgMCBvYmoKPDwvUHJvZHVjZXIoaVRleHSuIDUuNS4xMy4yIKkyMDAwLTIwMjAgaVRleHQgR3JvdXAgTlYgXChBR1BMLXZlcnNpb25cKSkvQ3JlYXRpb25EYXRlKEQ6MjAyMzEwMDQxNjE2MzkrMDUnMzAnKS9Nb2REYXRlKEQ6MjAyMzEwMDQxNjE2MzkrMDUnMzAnKT4+CmVuZG9iagp4cmVmCjAgNwowMDAwMDAwMDAwIDY1NTM1IGYgCjAwMDAwMDAzMTUgMDAwMDAgbiAKMDAwMDAwMDAxNSAwMDAwMCBuIAowMDAwMDAwNDAzIDAwMDAwIG4gCjAwMDAwMDAyMDMgMDAwMDAgbiAKMDAwMDAwMDQ1NCAwMDAwMCBuIAowMDAwMDAwNDk5IDAwMDAwIG4gCnRyYWlsZXIKPDwvU2l6ZSA3L1Jvb3QgNSAwIFIvSW5mbyA2IDAgUi9JRCBbPGNkYjRlMmVkODI3YzhjNmEyZjA3OGIxMTkwMjBjMGVkPjxjZGI0ZTJlZDgyN2M4YzZhMmYwNzhiMTE5MDIwYzBlZD5dPj4KJWlUZXh0LTUuNS4xMy4yCnN0YXJ0eHJlZgo2NTkKJSVFT0YK\", \"path\": \"/motivation.pdf\" }";

 try (OutputStream os = conection.getOutputStream()) {
 byte[] input = jsonString.getBytes(StandardCharsets.UTF_8);
 os.write(input, 0, input.length);
 }
 
 // Print Stataus code
 System.out.println("Status Code: "+conection.getResponseCode());

 // Get content from response and print in console. Use try with resource to close streams automatically
 try (BufferedReader br = new BufferedReader(new InputStreamReader(conection.getInputStream(), StandardCharsets.UTF_8))) {
 StringBuilder resp = new StringBuilder();
 String respLine = null;
 while ((respLine = br.readLine()) != null) {
 resp.append(respLine.trim());
 }
 
 System.out.println(resp.toString());
 }
	}
}

 

 

/VR