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");
            //setJwtTokens(connection);//设置jwtToken
            OutputStreamWriter paramout = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
            paramout.write(object.toString());
            paramout.flush();
            //LOG.warn("本次请求返回状态值" + connection.getResponseCode());
            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>
时间: 06-28

java之远程接口调用的相关文章

远程接口调用

1.1          第二部分:远程接口调用方式HttpClient 问题:现在我们已经开发好了接口了,那该如何调用这个接口呢? 答:使用Httpclient客户端. 1.1.1         Httpclient简介 1.1.1.1     什么是httpclient HttpClient 是 Apache Jakarta Common 下的子项目,用来提供高效的.最新的.功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议.实现了所有 HTTP

SmartRoute之远程接口调用和负载

基于接口的调用远比基于基础消息交互来得更简单和便于维护,特别在业务展现上,接口作为业务表现更适合其便利性.为了让SmartRoute更适合业务应用集成,在新的一年开始SmartRoute集成了远程接口调用功能.基于SmartRoute的基础特性,在这基础上扩展的接口调用会变得更简单灵活,其特别点如下:并不需要知道服务地址,只需要明确接口和方法即可以实现远程服务调用:无需任何配置即可实现负载和故障迁移.而这一系列的更利功能都归攻于SmartRoute基础建设! SmartRoute的远程接口调用是

EJB远程接口调用

一.EJB简介 EJB是sun的JavaEE服务器端组件模型,设计目标与核心应用是部署分布式应用程序.简单来说就是把已经编写好的程序(即:类)打包放在服务器上执行.凭借java跨平台的优势,用EJB技术部署的分布式系统可以不限于特定的平台.EJB (Enterprise JavaBean)是J2EE(javaEE)的一部分,定义了一个用于开发基于组件的企业多重应用程序的标准.其特点包括网络服务支持和核心开发工具(SDK). 在J2EE里,Enterprise Java Beans(EJB)称为J

springBoot使用feign实现远程接口调用和错误熔断

1.第一步,新建两个简单的springboot项目并创建rest接口 demo系统的rest接口 plus系统的调用接口 2.在项目pom文件里导入feign和hystrix的pom依赖包 <properties> <java.version>1.8</java.version> <spring-cloud.version>Greenwich.SR1</spring-cloud.version> </properties> <!

Java RMI远程方法调用

参考: 利用java-RMI进行大文件传输 RMI远程方法调用的简单方法和实例 RMI是类似RPC的一种远程方法调用协议,比RPC类型的WebService更简单,也可以跨进程访问 先来创建一个model或者javaBean,注意,该类必须实现序列化Serializable  public class Person implements Serializable {     private int id;     private String name;     private int age;

java通过JNI接口调用C语言-初级

JNI(java native interface):即java本地调用C的接口. 先看整体运行: 下面是过程: #vim test.java 1 public class test{ 2 3 public native static int add(int a, int b); //指明本地函数 4 static{ 5 System.loadLibrary("add"); //指定动态库 6 }; 7 8 public static void main(String args[]){

Java中socket接口调用

最近一个项目中接口通讯这一块主要是调用银联系统的socket接口,我方是客户端,即发送请求接收返回报文的一方.在贴代码之前,还是要了解一下关于socket的基础知识. Socket的基本概念 1.建立连接 当需要建立网络连接时,必须有一台机器运行一个程序,随时等候连接,而另一端的程序这对其发出连接请求.这一点同电话系统类似--必须有一方拨打电话,而另一方必须等候电话连通. 建立连接的过程为: (1)先在服务器端生成一个ServerSocket实例对象,随时监听客户端的连接请求. (2)当客户端需

以前写的一段aop,远程接口调用的日志。

using System;using System.Collections.Generic;using System.Linq;using System.Text; using Microsoft.Practices.Unity;using Microsoft.Practices.Unity.InterceptionExtension; namespace VirtualRemote.log4net{ public class LogHandler : ICallHandler { /// <s

[go]grpc远程接口调用实现

// grpc序列化/反序列化成对应语言的对象 // 1.写idl(数据类型+方法) // 2.生成对应语言的序列化/反序列化代码 // 3.方法需要自己实现 // 环境(将gopath/bin加入path) //安装grpc引擎 go get -u google.golang.org/grpc //安装grpc-go插件(适配go语言) go get -u github.com/golang/protobuf/protoc-gen-go //helloworld.proto // The re