title: RESTful web service with Zend Framework 2
body: <p>I'm developing a Zend Framework 2 module which represents a RESTful web service. The controller takes two parameters as input (from an external application), queries the specified database with those parameters and returns a JSON.</p>
  
  <p>AlbumController.php</p>
  
  <pre><code>&lt;?php
  namespace Album\Controller;
  
  
  use Album\Model\Album;
  use Album\Model\AlbumTable;
  use Zend\Mvc\Controller\AbstractRestfulController;
  use Zend\Http\Request;
  use Zend\View\Model\JsonModel;
  use Zend\Mvc\Controller\Plugin;
  
  class AlbumController extends AbstractRestfulController
  {
  
      /*public function indexAction()
      {
          return array();
      }*/
  
      protected $albumTable;
  
      public function getList()
      {
  
          $request = $this-&gt;getRequest();
  
          // if I set par1 and par statically, the service works
          $par1 = $request-&gt;getPost('par1');
          $par2 = $request-&gt;getPost('par2');
  
          $results = $this-&gt;getAlbumTable()-&gt;getAlbumByYearAndGenre($par1, $par2);
          $data = array();
  
          foreach ($results as $result) {
              $data[] = $result;
          }
  
          return new JsonModel(array(
              'Albums' =&gt; $data
          ));
      }
  
      public function getAlbumTable()
      {
          if (! $this-&gt;albumTable) {
              $sm = $this-&gt;getServiceLocator();
              $this-&gt;albumTable = $sm-&gt;get('Album\Model\AlbumTable');
          }
          return $this-&gt;albumTable;
      }
  
      public function get($id)
      {
          // TODO: Implement Method
      }
  
      public function create($data)
      {
          // TODO: Implement Method
      }
  
      public function update($id, $data)
      {
          // TODO: Implement Method
      }
  
      public function delete($id)
      {
          // TODO: Implement Method
      }
  }
  </code></pre>
  
  <p>AlbumTable.php</p>
  
  <pre><code>&lt;?php
  namespace Album\Model;
  
  use Zend\Db\TableGateway\TableGateway;
  use Zend\ServiceManager\ServiceLocatorAwareInterface;
  use Zend\ServiceManager\ServiceLocatorInterface;
  
  class AlbumTable implements ServiceLocatorAwareInterface
  
  {
  
  protected $tableGateway;
  protected $serviceLocator;
  protected $adapter;
  
  public function __construct(TableGateway $tableGateway)
  {
      $this-&gt;tableGateway = $tableGateway;
  }
  
  public function fetchAll()
  {
      $resultSet = $this-&gt;tableGateway-&gt;select();
      return $resultSet;
  }
  
  public function setServiceLocator(ServiceLocatorInterface $serviceLocator) {
      $this-&gt;serviceLocator = $serviceLocator;
  }
  
  public function getServiceLocator() {
      return $this-&gt;serviceLocator;
  }
  
  public function getAdapter()
  {
      if (!$this-&gt;adapter) {
          $sl = $this-&gt;getServiceLocator();
          $this-&gt;adapter = $sl-&gt;get('db2');
      }
      return $this-&gt;adapter;
  }
  
  public function getAlbumByYearAndGenre($par1, $par2)
  {
  
  
  
  
      $sql = "my query";
  
      $statement = $this-&gt;getAdapter()-&gt;query($sql);
      return $statement-&gt;execute();
  }
  </code></pre>
  
  <p>}</p>
  
  <p>The external application (an Android app) uses a JSONParser to retrieve some informations:</p>
  
  <pre><code>public class JSONParser {
  
      static InputStream is = null;
      static JSONObject jObj = null;
      static String json = "";
  
  
      public JSONParser() {
  
      }
  
  
      public JSONObject makeHttpRequest(String url, String method,
              List&lt;NameValuePair&gt; params) {
  
  
          try {
  
  
              if(method == "POST"){
  
                  DefaultHttpClient httpClient = new DefaultHttpClient();
                  HttpPost httpPost = new HttpPost(url);
                  httpPost.setEntity(new UrlEncodedFormEntity(params));
  
                  HttpResponse httpResponse = httpClient.execute(httpPost);
                  HttpEntity httpEntity = httpResponse.getEntity();
                  is = httpEntity.getContent();
                  httpClient.close();
              }else if(method == "GET"){
  
                  DefaultHttpClient httpClient = new DefaultHttpClient();
                  String paramString = URLEncodedUtils.format(params, "utf-8");
                  url += "?" + paramString;
                  HttpGet httpGet = new HttpGet(url);
  
                  HttpResponse httpResponse = httpClient.execute(httpGet);
                  HttpEntity httpEntity = httpResponse.getEntity();
                  is = httpEntity.getContent();
                  httpClient.close();
              }          
  
          } catch (UnsupportedEncodingException e) {
              e.printStackTrace();
          } catch (ClientProtocolException e) {
              e.printStackTrace();
          } catch (IOException e) {
              e.printStackTrace();
          }
  
          try {
              BufferedReader reader = new BufferedReader(new InputStreamReader(
                      is, "iso-8859-1"));
              StringBuilder sb = new StringBuilder();
              String line = null;
              while ((line = reader.readLine()) != null) {
                  sb.append(line + "\n");
              }
              is.close();
              json = sb.toString();
          } catch (Exception e) {
             e.printStackTrace();
          }
  
  
          try {
              jObj = new JSONObject(json);
          } catch (JSONException e) {
              e.printStackTrace();
          }
  
          return jObj;
  
      }
  }
  </code></pre>
  
  <p>To simulate the app's behaviour I created a JSONParserTest:</p>
  
  <pre><code>public class JSONParserTest {
      public static void main(String[] args) {
          JSONParser jparser = new JSONParser();
          String url = "myurl";
          int par1 = 0;
          String par2 = "..."
          List&lt;NameValuePair&gt; params = new ArrayList&lt;NameValuePair&gt;();
          params.add(new BasicNameValuePair("par1", Integer.toString(par1)));
          params.add(new BasicNameValuePair("par2", par2);
          JSONObject json = jparser.makeHttpRequest(url, "POST", params);
          try {
              JSONArray jarray = json.getJSONArray("Albums");
              System.out.println(jarray.toString());
              System.out.println(json.toString());
              for(int i = 0; i &lt; jarray.length(); i++)
              {
                  JSONObject object = jarray.getJSONObject(i);
                  System.out.println(object.getString("par1"));
                  System.out.println(object.getString("par2"));
              } 
  
          } catch (JSONException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
          }
  
      }
  }
  </code></pre>
  
  <p>Problem is if I set the parameters statically in the controller and I open the path, I get the JSON. But if I bind the parameters to the request, it seems like zend is not getting them (and I get an empty JSON). In fact, this is the exception:</p>
  
  <pre><code>org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1]
      at org.json.JSONTokener.syntaxError(JSONTokener.java:433)
      at org.json.JSONObject.&lt;init&gt;(JSONObject.java:188)
      at org.json.JSONObject.&lt;init&gt;(JSONObject.java:314)
      at com.example.mypackage.jclasses.JSONParser.makeHttpRequest(JSONParser.java:89)
      at com.example.mypackage.jclasses.JSONParserTest.main(JSONParserTest.java:22)
  Exception in thread "main" java.lang.NullPointerException
      at com.example.mypackage.jclasses.JSONParserTest.main(JSONParserTest.java:24)
  </code></pre>
  
  <p>(Line 22 is <code>JSONObject json = jparser.makeHttpRequest(url, "POST", params);</code> and line 24 is: <code>JSONArray jarray = json.getJSONArray("Albums");</code>)</p>