java之远程接口调用

Posted code.world

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java之远程接口调用相关的知识,希望对你有一定的参考价值。

一、通过地址栏传值

1、项目结构

2、pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>test.com</groupId>
  <artifactId>test-com</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>test-com Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>

    <!-- spring begin -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    <!-- spring end -->

    <!-- Spring AOP + AspectJ by shipengzhi -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aspects</artifactId>
      <version>3.0.6.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjrt</artifactId>
      <version>1.6.11</version>
    </dependency>
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.6.11</version>
    </dependency>
    <dependency>
      <groupId>cglib</groupId>
      <artifactId>cglib</artifactId>
      <version>2.1_3</version>
    </dependency>
    <!-- end -->

    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>net.sf.json-lib</groupId>
      <artifactId>json-lib</artifactId>
      <version>2.4</version>
      <classifier>jdk15</classifier>
    </dependency>
  </dependencies>
  <build>
    <finalName>test-com</finalName>
  </build>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <spring.version>3.1.2.RELEASE</spring.version>
  </properties>
</project>

3、web.xml

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">
  <display-name>Archetype Created Web Application</display-name>

  <servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <!-- 设置dispatchservlet的匹配模式,通过把dispatchservlet映射到/,默认servlet会处理所有的请求,包括静态资源 -->
  <servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

  <!-- 字符集过滤器 -->
  <filter>
  <filter-name>encodingFilter</filter-name>
  <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  <init-param>
    <param-name>encoding</param-name>
    <param-value>UTF-8</param-value>
  </init-param>
  <init-param>
  <param-name>forceEncoding</param-name>
    <param-value>true</param-value>
  </init-param>
  </filter>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

4、dispatcher-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/mvc
            http://www.springframework.org/schema/mvc/spring-mvc.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd"
       default-lazy-init="true">

    <!-- 通过mvc:resources设置静态资源,这样servlet就会处理这些静态资源,而不通过控制器 -->
    <!-- 设置不过滤内容,比如:css,jquery,img 等资源文件 -->
    <mvc:resources location="/*.html" mapping="/**.html" />
    <mvc:resources location="/css/*" mapping="/css/**" />
    <mvc:resources location="/js/*" mapping="/js/**" />
    <mvc:resources location="/images/*" mapping="/images/**" />

    <!-- 添加注解驱动 -->
    <mvc:annotation-driven />
    <!-- 默认扫描的包路径 -->
    <context:component-scan base-package="com.*" />

    <!-- mvc:view-controller可以在不需要Controller处理request的情况,转向到设置的View -->
    <!-- 像下面这样设置,如果请求为/,则不通过controller,而直接解析为/index.jsp -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
        <property name="viewClass"
                  value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <!--  日志自定义注解拦截器 -->
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/**"/>
            <bean class="com.log.SystemLogAspect"></bean>
        </mvc:interceptor>
    </mvc:interceptors>

</beans>

5、TestController.java

package com.controller;

import com.log.Log;
import com.remote.RemoteDemo;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * Created by sunjf on 2016/6/26.
 */
@Controller
public class TestController {

    @Log(desc = "log测试")
    @RequestMapping(value = "test1")
    public String test1(){
        String result = RemoteDemo.remoteJsonRequest("http://localhost:8080/test2?username=sun&password=123", 5000, new JSONObject());
        System.out.println(result);
        return "success";
    }

}

6、RemoteDemo.java

package com.remote;

import net.sf.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by Administrator on 2016/6/27.
 */
public class RemoteDemo {

    public static String remoteJsonRequest(String url, int timeout, JSONObject object) {
        URL connect;
        StringBuffer data = new StringBuffer();
        try {
            connect = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) connect.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setReadTimeout(timeout);
            connection.setRequestProperty("Content-Type", "application/json");
            OutputStreamWriter paramout = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
            paramout.write(object.toString());
            paramout.flush();
            InputStream inputStream = connection.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
            BufferedReader reader = new BufferedReader(inputStreamReader);

            String line;
            while ((line = reader.readLine()) != null) {
                data.append(line);
            }
            paramout.close();
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return data.toString();
    }


}

7、调用另一项目中的借口(TestController.java)

package com.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by sunjf on 2016/6/26.
 */
@Controller
public class TestController {

    @RequestMapping(value = "test2")
    @ResponseBody
    public String test2(String username, String password){
        System.out.println(username + " | " + password);
        return username + " | " + password;
    }

}

8、index.jsp

<html>
<body>
<h2>Hello World!</h2>
<form action="test1" method="post">
    <input type="submit" name="submit">
</form>

</body>
</html>

9、success.jsp

<html>
<body>
<h2>Hello Success!</h2>
</body>
</html>

 二、同过jsonObject传值,通过object接收

1、TestController.java,请求端发送请求

package com.controller;

import com.log.Log;
import com.remote.RemoteDemo;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * Created by sunjf on 2016/6/26.
 */
@Controller
public class TestController {

    @Log(desc = "log测试")
    @RequestMapping(value = "test1")
    public String test1(){
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("username", "sun");
        jsonObject.put("password", "123");
        String result = RemoteDemo.remoteJsonRequest("http://localhost:8080/test2", 5000, jsonObject);
        System.out.println(result);
        return "success";
    }

}

2、TestController.java,被访问端接口

package com.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * Created by sunjf on 2016/6/26.
 */
@Controller
public class TestController {

    @RequestMapping(value = "test2", method = RequestMethod.POST, produces="application/json")
    @ResponseBody
    public String test2(@RequestBody User user){
        System.out.println(user.toString());
        return user.toString();
    }

}

注:注意此时的@RequestBody注解,为此需要在被访问端引入依赖

<dependency>
      <groupId>org.codehaus.jackson</groupId>
      <artifactId>jackson-mapper-asl</artifactId>
      <version>1.9.8</version>
      <type>jar</type>
      <scope>compile</scope>
    </dependency>

3、User.java,接收实体类

package com.controller;

/**
 * Created by Administrator on 2016/6/28.
 */
public class User {

    private String username;
    private String password;

    @Override
    public String toString() {
        return "User{" +
                "username=\'" + username + \'\\\'\' +
                ", password=\'" + password + \'\\\'\' +
                \'}\';
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

 

以上是关于java之远程接口调用的主要内容,如果未能解决你的问题,请参考以下文章

java 调用远程接口 webservices 原理和流程

Java中面向对象的三大特性之封装

java远程调用接口的原理和范例,谢谢

使用java代码本地测试远程rpc接口

SmartRoute之远程接口调用和负载

Java代码审计之RCE远程命令执行