Search code examples
javanullpointerexceptionhttpconnection

Getting the value null of the variable


Here is my code in this code the value inside the try block I am getting the value of httpconn = null but in the first line I am storing the value into the variable httpconn in the first line why it so. I am getting nullpointerexception.

public static String requestToken()
    {
         String url = Const.REQUEST_TOKEN_URL;
         String header = oauth_header(url, HttpProtocolConstants.HTTP_METHOD_GET);
         String requestTokenUrl = concatURL(url, header);
         HttpConnection httpConn = null;
         InputStream input = null;
         try
         {

            httpConn = (HttpConnection) Connector.open(requestTokenUrl); // kris connection
             httpConn.setRequestMethod(HttpProtocolConstants.HTTP_METHOD_GET);
             httpConn.setRequestProperty("WWW-Authenticate","OAuth realm=http://twitter.com/");
             httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

             input = httpConn.openDataInputStream();
             int resp = httpConn.getResponseCode();
             if (resp == HttpConnection.HTTP_OK) 
             {

                 StringBuffer buffer = new StringBuffer();
                 int ch;
                 while ( (ch = input.read()) != -1)
                 {
                     buffer.append( (char) ch);
                 }
                 String content = buffer.toString();
                 Const.token = content.substring(content.indexOf((Const.OAUTH_TOKEN+"="))+(Const.OAUTH_TOKEN+"=").length(), content.indexOf('&'));
                 Const.tokenSecret = content.substring(content.indexOf((Const.OAUTH_TOKEN_SECRET+"="))+(Const.OAUTH_TOKEN_SECRET+"=").length(), content.length());

                 message = httpConn.getResponseMessage();


             }
             return message;//(getTwitterMessage(httpConn.getResponseCode()));
            }
            catch (IOException e) 
            {
                return "exception";
            }
            catch (Exception nc) 
            {
                return "noConnection";
            } finally {
             try {
                 httpConn.close();
                 input.close();
             } catch (IOException e) {
                 e.printStackTrace();
             }

Solution

  • In the finally block, do

    if (httpConn != null)
        httpConn.close();
    
    if (input != null)
        input.close();
    

    If e.g. in the code you posted Connector.open() throws an exception, httpConn will not be initialized to anything other than null. You will catch that exception and want to return information related to it but before returning, you try to access a null pointer (in the finally block) which raises the NullPointerException.