不同java项目之间接口的相互调用

最近一个项目需要将某个功能独立成一个单独的项目后给原项目调用,记录一下.大致思路就是项目A利用工具类调用项目B的接口进行一个功能实现,记录一下

工具类

package com.xxx.tools.utils;

import jdk.internal.instrumentation.Logger;
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

public class HttpUtil {
   public static String doPost2(String url, JSONObject param) {
        HttpPost httpPost = null;
        String result = null;
        try {
            HttpClient client = new DefaultHttpClient();
            httpPost = new HttpPost(url);
            if (param != null) {
                StringEntity se = new StringEntity(param.toString(), "utf-8");
                httpPost.setEntity(se); // post方法中,加入json数据
                httpPost.setHeader("Content-Type", "application/json");
            }

            HttpResponse response = client.execute(httpPost);
            if (response != null) {
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    result = EntityUtils.toString(resEntity, "utf-8");
                }
            }

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return result;
    }
}

A项目调用接口

//项目B的接口地址,需要加http://
String url="http://127.0.0.1:8088/erp/print/printText";
JSONObject jsonObject=new JSONObject();
jsonObject.put("content",content);
jsonObject.put("origin_id",origin_id);
HttpUtil.doPost2(url,jsonObject);

B项目的controller类

@RestController
@RequestMapping("/print")
public class PrintController {

    @Autowired
    private PrintOrder printOrder;

    @ResponseBody
    @RequestMapping(value = "/printText",method = RequestMethod.POST)
    public String addPrintOrder(@RequestBody PrintText printText)throws Exception{

        String result="";

        String content=printText.getContent();
        String origin_id=printText.getOrigin_id();
        result= printOrder.addPrintOrder(content,origin_id);

        System.out.println("result-----"+result);
        return result;

    }
}

 

你可能感兴趣的:(不同java项目之间接口的相互调用)