怎么从后端调用别的项目的借口

最近遇到在自己的代码中调用公司别的项目的接口。自己看网上的代码调通了。

package com.xz.app.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class PostUtil {
    /**
     *
     * @param url
     * @param query  请求文,不是请求url
     * @param token
     * @return
     * @throws Exception
     */
    public static String load(String url, String query,String token) throws Exception {
        URL restURL = new URL(url);
        /*
         * 此处的urlConnection对象实际上是根据URL的请求协议(此处是http)生成的URLConnection类 的子类HttpURLConnection
         */
        HttpURLConnection conn = (HttpURLConnection) restURL.openConnection();
        //请求方式
        conn.setRequestMethod("POST");
        //设置是否从httpUrlConnection读入,默认情况下是true; httpUrlConnection.setDoInput(true);
        conn.setDoOutput(true);
        //allowUserInteraction 如果为 true,则在允许用户交互(例如弹出一个验证对话框)的上下文中对此 URL 进行检查。
        conn.setAllowUserInteraction(false);
        conn.setRequestProperty("token", token);

        conn.setRequestProperty("Content-type", "application/json");

        //conn.connect();

        PrintStream ps = new PrintStream(conn.getOutputStream());
        ps.print(query);
        ps.close();

        BufferedReader bReader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

        String line, resultStr = "";

        while (null != (line = bReader.readLine())) {
            resultStr += line;
        }
        System.out.println("---" + resultStr);
        bReader.close();
        return resultStr;
    }
}

参数token是请求报头的参赛名称,需要自己改掉。

@RequestHeader("token") @ApiParam(value = "权限校验") String token

如这个

如果是这种

@RequestParam("companyId1") @ApiParam(value = "商家id1") int companyId1

那么在url后面加就是如?userId=1

如果是

@RequestBody("companyId1")

那就传query就行

猜你喜欢

转载自blog.csdn.net/xu505928168/article/details/90579443
今日推荐