2

我们有如下要求

  1. 集成系统需要调用我们的服务
  2. 我们的服务需要调用 FlipKart 服务并在请求中附加令牌
  3. 将响应返回到集成系统

上面应该可以无缝地用于 GET 和 PUT 请求。

我在 Eclipse 中开发了一个 REST 项目,并且能够将 GET 和 PUT 响应返回到 Integration。

不过问题很少

  1. 在 Get Requests 中,我们显式设置标头并为 appication/json 生成注释。我们如何为所有类型的请求设置它?
  2. 在 Post Response 中,我们没有得到完整的响应,并且我们无法在响应中设置应用程序类型(不确定如何!)
  3. 如果应用程序类型是 pdf、img 等,所有这些请求都会失败。

有人可以帮忙吗?

到目前为止实现的代码:

 @GET
    @Path("{pathvalue : (.+)?}")
    @Produces("{application/json;application/octet-stream}")
    public String getFlipKartResponse(@Context UriInfo uriInfo, @PathParam("pathvalue") String pathValue, @Context  HttpServletRequest request) throws ClassNotFoundException,IOException {
        String methodName = "getFlipKartResponse";
        if (LOGGER.isLoggable(Level.FINER)) {
            LOGGER.entering(CLASSNAME, methodName);
        }       
        MultivaluedMap<String, String> queryParams = uriInfo.getQueryParameters();

        //if(null == flipkartUrl || flipkartUrl.isEmpty())
            flipkartUrl = config.getProperty(ServiceConstants.FLIPKART_URL);
        String queryParam = new String();
        Iterator<String> iterator = queryParams.keySet().iterator();

        while (iterator.hasNext()) {
            String parameter = iterator.next();
            queryParam = queryParam.concat(parameter + ServiceConstants.EQUALS + queryParams.getFirst(parameter) + ServiceConstants.AMPERSAND);
        }
        String modifiedflipkartUrl = flipkartUrl.concat(pathValue).concat(ServiceConstants.QUESTION).concat(queryParam);
        if (modifiedflipkartUrl.endsWith(ServiceConstants.QUESTION) || modifiedflipkartUrl.endsWith(ServiceConstants.AMPERSAND)) {
            modifiedflipkartUrl = modifiedflipkartUrl.substring(0, modifiedflipkartUrl.length()-1);
        }

        LOGGER.log(Level.INFO, "Flipkart URL framed : "+ modifiedflipkartUrl);

        url = new URL(modifiedflipkartUrl);
        connection = (HttpsURLConnection) url.openConnection();
        setHeadersInConnectionObject(url, connection, request.getMethod());
        return handleInvalidToken(connection.getResponseCode(), request);
    }

    private String handleInvalidToken(int responseCode, HttpServletRequest request){
        try {
        if (connection.getResponseCode() == 401) {
               LOGGER.log(Level.INFO, "ResponseCode " + connection.getResponseCode());                 
               connection.disconnect(); 
               regenerateAccessToken();
               connection = (HttpsURLConnection) url.openConnection();
               setHeadersInConnectionObject(url, connection, request.getMethod());
               inputLine =  new BufferedReader(new InputStreamReader(connection.getInputStream()));
        } else if (connection.getResponseCode() == 200) {
               inputLine =  new BufferedReader(new InputStreamReader(connection.getInputStream()));
        } else {
               inputLine =  new BufferedReader(new InputStreamReader(connection.getErrorStream()));
        }

        String responseInputLine;
        String responseMessage = "";
        while (null != (responseInputLine = inputLine.readLine())) {
               responseMessage = responseMessage + responseInputLine;
        }
        inputLine.close();  
        connection.disconnect();
        return responseMessage;          
        } catch (Exception e) {
               LOGGER.log(Level.SEVERE,"Exception occured while calling service.Please try again after sometime : ", e);
               return this.handleErrorResponse("Exception occured while calling service.Please try again after sometime.");
        }
  }


    private void regenerateAccessToken() throws ClassNotFoundException, IOException, SQLException{
        TokenGenerator tokenGenerator = new TokenGenerator();
        accessToken= tokenGenerator.getAccessToken();
    }

    @POST
    @Path("{pathvalue : (.+)?}")
    @Produces({"application/json;application/octet-stream"})
    public String getFlipKartPostResponse(@Context UriInfo uriInfo, @PathParam("pathvalue") String pathValue,@Context  HttpServletRequest requestBody) throws ClassNotFoundException,IOException, SQLException {
        String methodName = "getFlipKartPostResponse";
        if (LOGGER.isLoggable(Level.FINER)) {
            LOGGER.entering(CLASSNAME, methodName);
        }

        //if(null == flipkartUrl || flipkartUrl.isEmpty())
            flipkartUrl = config.getProperty(ServiceConstants.FLIPKART_URL);
        String modifiedflipkartUrl = flipkartUrl + pathValue;
        url = new URL(modifiedflipkartUrl);
        LOGGER.log(Level.INFO, "Flipkart URL framed : "+ flipkartUrl);

        connection = (HttpsURLConnection) url.openConnection();
        setHeadersInConnectionObject(url, connection, requestBody.getMethod());

        InputStream requestInputStream = requestBody.getInputStream();
        String reqBody = getStringFromInputStream(requestBody.getInputStream());

        OutputStream outputStream = connection.getOutputStream();
        outputStream.write(reqBody.getBytes());
        outputStream.flush();

        if(connection.getResponseCode() == 401) {
            connection.disconnect(); 
            regenerateAccessToken();
            connection = (HttpsURLConnection) url.openConnection();
            setHeadersInConnectionObject(url, connection, requestBody.getMethod());

            outputStream = connection.getOutputStream();
            outputStream.write(reqBody.getBytes());
            outputStream.flush();
        }
        String output = getStringFromInputStream (connection.getInputStream());
        connection.disconnect();

        if (LOGGER.isLoggable(Level.FINER)) {
            LOGGER.exiting(CLASSNAME, methodName);
        }   
        return output;
    }



    private static String getStringFromInputStream(InputStream is) {
        String methodName = "getStringFromInputStream";
        if (LOGGER.isLoggable(Level.FINER)) {
            LOGGER.entering(CLASSNAME, methodName);
        }
        BufferedReader br = null;
        StringBuilder sb = new StringBuilder();
        String line;
        try {
            br = new BufferedReader(new InputStreamReader(is));
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        if (LOGGER.isLoggable(Level.FINER)) {
            LOGGER.exiting(CLASSNAME, methodName);
        }   
        return sb.toString();

    }
    /**
     * Method to generate the access token
     * @return String - Access token
     * @throws IOException
     */
    private String getAccessToken() throws IOException {
        if (null != accessToken) {
            return accessToken;
        } else {
            url = getClass().getResource(ServiceConstants.ACCESS_TOKEN_CONFIG_PATH);
            file = new File(url.getPath());     
            reader = new BufferedReader (new InputStreamReader (new FileInputStream (file), ServiceConstants.UTF_ENCODING));        
            accessToken = reader.readLine();
            reader.close();
            return accessToken;
        }
    }

    /**
     * Method to construct error response for exception scenario
     * @param errorMessage
     * @return
     */
    private String handleErrorResponse(String errorMessage) {
        String methodName = "handleErrorResponse";
        if (LOGGER.isLoggable(Level.FINER)) {
            LOGGER.entering(CLASSNAME, methodName);
        }

        JSONObject errorResponse = new JSONObject();
        JSONArray errorMsg = new JSONArray();
        errorResponse.put(ServiceConstants.STATUS, ServiceConstants.STATUS_FAILED);
        errorResponse.put(ServiceConstants.ERROR_MESSAGE, errorMessage);
        errorMsg.add(errorResponse);

        if (LOGGER.isLoggable(Level.FINER)) {
            LOGGER.exiting(CLASSNAME, methodName);
        }       
        return errorResponse.toString();        
    }

    /**
     * Method to form the connection object 
     * @param url
     * @param connection
     * @param requestType
     * @throws IOException
     */
    private void setHeadersInConnectionObject(URL url, HttpsURLConnection connection, String requestType) throws IOException {
        String methodName = "setHeadersInConnectionObject";
        if (LOGGER.isLoggable(Level.FINER)) {
            LOGGER.entering(CLASSNAME, methodName);
        }

        if (null == accessToken) {
            getAccessToken();
        }
        connection.setRequestMethod(requestType);
        connection.setRequestProperty(ServiceConstants.AUTHORIZATION, ServiceConstants.BEARER + accessToken);
        connection.setDoOutput(true);

        if (requestType.equals(ServiceConstants.REQUEST_TYPE_GET)) {            
            connection.setRequestProperty(ServiceConstants.ACCEPT_HEADER, ServiceConstants.ACCEPT_ALL);
            //connection.setRequestProperty(ServiceConstants.ACCEPT_HEADER, ServiceConstants.APPLICATION_JSON);
        }

        if (requestType.equals(ServiceConstants.REQUEST_TYPE_POST)) {
            connection.setRequestProperty(ServiceConstants.ACCEPT_HEADER, ServiceConstants.APPLICATION_JSON);           
            connection.setRequestProperty(ServiceConstants.CONTENT_TYPE_HEADER, ServiceConstants.APPLICATION_JSON);
            //connection.setDoInput(true);
        }

        if (LOGGER.isLoggable(Level.FINER)) {
            LOGGER.exiting(CLASSNAME, methodName);
        }
    }
4

0 回答 0