Saturday, January 12, 2019

Java code that will invoke a POST method to a RESTlet

Below are sample codes that can be used to invoke a POST method to a RESTlet

RESTlet code:

function restPost(datain){

var process = new Object();
process.success = 'Welcome to '+datain.name+'!';
return process;

}

Java code:

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;

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

  // Set Credentials
  String account = "AccountNumber";
  String email = "Username";
  String pass = "Password";
  String role = "3"; // 3 is the role id for Administrators

  // Set the external URL of the RESTlet found on its deployment page.
  URL url = new URL(
    "https://rest.netsuite.com/app/site/hosting/restlet.nl?script=431&deploy=1");
  HttpsURLConnection urlConn = (HttpsURLConnection) url.openConnection();

  // Set the parameters to be passed to the RESTlet
  String postParam = "{\"name\": \"NetSuite\"}";

  urlConn.setRequestMethod("POST");

  urlConn.setDoOutput(true);
  urlConn.setDoInput(true);

  urlConn.setRequestProperty("Content-Type", "application/json");
  urlConn.setRequestProperty("Host", "https://rest.netsuite.com");
  urlConn.setRequestProperty("Authorization", "NLAuth nlauth_account="
    + account + ", nlauth_email=" + email + ",nlauth_signature="
    + pass + ", nlauth_role=" + role);

  // Send request
  DataOutputStream wr = new DataOutputStream(urlConn.getOutputStream());
  wr.writeBytes(postParam);
  wr.flush();
  wr.close();

  // Get Response
  InputStream is = urlConn.getInputStream();
  BufferedReader rd = new BufferedReader(new InputStreamReader(is));
  String line;
  StringBuffer response = new StringBuffer();
  while ((line = rd.readLine()) != null) {
   response.append(line);
   response.append('\r');
  }
  rd.close();
  System.out.println(response.toString());

  // Output should look like this, {"success":"Welcome to NetSuite!"}

 }
}

No comments:

Post a Comment