Wednesday, October 31, 2018

JAVA Code that will Invoke a GET Method to a RESTlet

This article will show users invoke a GET method to a RESTlet in JAVA.

RESTlet Code:

//simple restlet code that will return {"sayhi": "Hello World"}
function restTest(){
var o = new Object();
o.sayhi = 'Hello World! ';
return o;

JAVA Code:

	try {		URL url = new URL("");// external url of the RESTlet that can be found in the deployment of the RESTlet script		HttpsURLConnection urlConn = (HttpsURLConnection) url.openConnection();		urlConn.setRequestMethod("GET"); //set GET method		urlConn.setAllowUserInteraction(false); 		urlConn.setDoOutput(true);     		urlConn.setRequestProperty( "Content-type", "application/json" );// set Content type		urlConn.setRequestProperty( "Authorization", "NLAuth nlauth_account=accountid,,nlauth_signature=password, nlauth_role=3" );// set credentials (role 3 is the Admin role)		int rspCode = urlConn.getResponseCode();// get the response based from the RESTlet (HTTP response)		System.out.println(rspCode);		// read what the RESTlet returns		BufferedReader br = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));		StringBuilder sb = new StringBuilder();		String line;		while ((line = br.readLine()) != null) 			{			sb.append(line+"\n");			}		br.close();		System.out.println(sb.toString()); //RESTlet will return {"sayhi": "Hello World"}	   } 		catch (MalformedURLException e) 		{ e.printStackTrace();}		catch (IOException e) 		{ e.printStackTrace();}

DISCLAIMER: The sample code described herein is provided on an "as is" basis, without warranty of any kind, to the fullest extent permitted by law. Netsuite Inc. does not warrant or guarantee the individual success developers may have in implementing the sample code on their development platforms or in using their own Web server configurations.

Netsuite Inc. does not warrant, guarantee or make any representations regarding the use, results of use, accuracy, timeliness or completeness of any data or information relating to the sample code. Netsuite Inc. disclaims all warranties, express or implied, and in particular, disclaims all warranties of merchantability, fitness for a particular purpose, and warranties related to the code, or any service or software related thereto.

Netsuite Inc. shall not be liable for any direct, indirect or consequential damages or costs of any type arising out of any action taken by you or others related to the sample code


No comments:

Post a Comment