服务间http调用简单案例(通过httpUrlConnection)

URLConnections 类方法
openConnection() 返回一个 java.net.URLConnection。
例如:
如果你连接HTTP协议的URL, openConnection() 方法返回 HttpURLConnection 对象。
如果你连接的URL为一个 JAR 文件, openConnection() 方法将返回 JarURLConnection 对象。
代码如下:

客户端
package com.markor.url;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang.StringUtils;
import org.junit.Test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;

/**
 * @author: caichangmeng <[email protected]>
 * @date: 2018/10/22
 * @module: 类所属模块
 * @describe: urlConnection 练习
 * @version: v1.0
 */
public class UrlConnectionTest {

    public static void sendDemo(String targetUrl, String requestMethod, String contentType, String outputStr) throws IOException {

        URL url = new URL(targetUrl);
        URLConnection urlConnection = url.openConnection();
        HttpURLConnection connection = null;
        if (urlConnection instanceof HttpURLConnection) {
            connection = (HttpURLConnection) urlConnection;
            connection.setRequestMethod(requestMethod);
        } else {
            System.out.println("url 非 http请求");
            return;
        }
        if (StringUtils.equalsIgnoreCase("json", contentType)) {
            connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        }
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.connect();
        //往服务器端写内容 也就是发起http请求需要带的参数
        if (null != outputStr) {
            OutputStream os = connection.getOutputStream();
            os.write(outputStr.getBytes("utf-8"));
            //os.close();
        }
        System.out.println("contentType: " + connection.getContentType());
        BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
        StringBuffer sb = new StringBuffer();
        String current;
        while ((current = br.readLine()) != null) {
            // sb.append(current);
            System.out.println(current);
        }
        System.out.println(sb.toString());
    }

    @Test
    public void notArgus() throws IOException {
        sendDemo("http://localhost:8081/notArgus", "GET", null, null);
    }

    /**
     * @Date:     2018/10/22
     * @describe: get - 传值.
     */
    @Test
    public void argus() throws IOException {
        sendDemo("http://localhost:8081/argus?path=path-success", "GET", null, null);
    }

    /**
     * @Date:     2018/10/22
     * @describe: post.
     */
    @Test
    public void postNotArgus() throws IOException {
        sendDemo("http://localhost:8081/postNotArgus", "POST", null, null);
    }

    /**
     * @Date:     2018/10/22
     * @describe: post - 表单模式传值.
     */
    @Test
    public void postArgus() throws IOException {
        sendDemo("http://localhost:8081/postArgus", "POST", null, "pageNum=1&pageSize=10");
    }

    /**
     * @Date:     2018/10/22
     * @describe: post, json模式传值.
     */
    @Test
    public void postJson() throws IOException {
        Map<String, Integer> map = new HashMap<>();
        map.put("pageSize", 10);
        map.put("pageNum", 1);
        sendDemo("http://localhost:8081/postJson", "POST", "json", JSON.toJSONString(map));
    }
}
服务端
package com.markor.template.controller.url;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * @author: caichangmeng <[email protected]>
 * @date: 2018/10/22
 * @module: 类所属模块
 * @describe:
 * @version: v1.0
 */
@RestController
public class UrlController {

    /**
     * @Date:     2018/10/22
     * @describe: 无参请求 - get
     * @return : success: 成功
     * @throws:
     * @since:    1.0.0
     * @JIRA:
     */
    @GetMapping("notArgus")
    public String notArgus() {
        return "get - success";
    }

    /**
     * @Date:     2018/10/22
     * @describe: 有参请求
     * @param path :
     * @return : path
     * @throws:
     * @since:    1.0.0
     * @JIRA:
     */
    @GetMapping("argus")
    public String argus(String path) {
        return path;
    }

    /**
     * @Date:     2018/10/22
     * @describe: 无参请求 - post
     * @param null :
     * @return : null
     * @throws:
     * @since:    1.0.0
     * @JIRA:
     */
    @PostMapping("postNotArgus")
    public String postNotArgus() {
        return "post - success";
    }

    @PostMapping("postArgus")
    public UrlBean postArgus(UrlBean bean) {
        return bean;
    }

    @PostMapping("postJson")
    public String postJson(@RequestBody Map<String, Integer> param) {
        int pageNum = param.get("pageNum");
        int pageSize = param.get("pageSize");
        return "pageNum: "+ pageNum +"; pageSize: " + pageSize;
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_43503284/article/details/83380758