Java调用Http接口(2)--HttpURLConnection调用Htt…

2019-11-23 16:03:01来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

Java调用Http接口(2)--HttpURLConnection调用Http接口

HttpURLConnection是JDK自身提供的网络类,不需要引入额外的jar包。文中所使用到的软件版本:Java 1.8.0_191。

1、GET请求

public static void get() {
    HttpURLConnection connection = null;
    try {
        String requestPath = "http://localhost:8080/webframe/demo/test/getUser?userId=1000&userName=" + URLEncoder.encode("李白", "utf-8");
        URL url = new URL(requestPath);
        //设置代理
        //InetSocketAddress addr = new InetSocketAddress("127.0.0.1", 8888);  
        //Proxy proxy = new Proxy(Proxy.Type.HTTP, addr);
        //connection = (HttpURLConnection)url.openConnection(proxy);
        
        connection = (HttpURLConnection)url.openConnection();
        connection.setRequestMethod("GET");
        connection.connect();
        
        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            byte[] b = getBytesFromInputStream(connection.getInputStream());
            String back = new String(b);
            System.out.println("GET返回结果:" + back);
        } else {
            System.out.println("GET请求状态码:" + connection.getResponseCode());
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        connection.disconnect();
    }
}

2、POST请求(发送键值对数据)

public static void post() {
    HttpURLConnection connection = null;
    try {
        String requestPath = "http://localhost:8080/webframe/demo/test/getUser";
        URL url = new URL(requestPath);
        connection = (HttpURLConnection)url.openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.connect();
        
        String param = "userId=1000&userName=李白";
        setBytesToOutputStream(connection.getOutputStream(), param.getBytes());
        
        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            byte[] b = getBytesFromInputStream(connection.getInputStream());
            String back = new String(b);
            System.out.println("POST返回结果:" + back);
        } else {
            System.out.println("POST返回状态码:" + connection.getResponseCode());
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        connection.disconnect();
    }
}

3、POST请求(发送JSON数据)

public static void post2() {
    HttpURLConnection connection = null;
    try {
        String requestPath = "http://localhost:8080/webframe/demo/test/addUser";
        URL url = new URL(requestPath);
        connection = (HttpURLConnection)url.openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-type", "application/json");
        connection.connect();
        
        String param = "{\"userId\": \"1001\",\"userName\":\"杜甫\"}";
        setBytesToOutputStream(connection.getOutputStream(), param.getBytes());
        
        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            byte[] b = getBytesFromInputStream(connection.getInputStream());
            String back = new String(b);
            System.out.println("POST2返回结果:" + back);
        } else {
            System.out.println("POST2返回状态码:" + connection.getResponseCode());
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        connection.disconnect();
    }
}

4、上传文件及发送键值对数据

4.1、分析数据结构

通过抓包工具分析页面表单上传文件的过程,可以看出传输数据的结构:

 

4.2、根据分析出的数据结构编写代码

public static void multi() {
    String BOUNDARY = java.util.UUID.randomUUID().toString();
    String TWO_HYPHENS = "--";
  String LINE_END = "\r\n";
    HttpURLConnection connection = null;
    try {
        String requestPath = "http://localhost:8080/webframe/demo/test/multi";
        URL url = new URL(requestPath);
        connection = (HttpURLConnection)url.openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestProperty("Content-type", "multipart/form-data; BOUNDARY=" + BOUNDARY);
        connection.connect();
        
        StringBuffer sb = new StringBuffer();
        //封装键值对数据1
        sb.append(TWO_HYPHENS).append(BOUNDARY).append(LINE_END);
        sb.append("Content-Disposition: form-data; name=\"param1\"").append(LINE_END);
        sb.append(LINE_END);
        sb.append("参数1").append(LINE_END);
        
        //封装键值对数据2
        sb.append(TWO_HYPHENS).append(BOUNDARY).append(LINE_END);
        sb.append("Content-Disposition: form-data; name=\"param2\"").append(LINE_END);
        sb.append(LINE_END);
        sb.append("参数2").append(LINE_END);
        
        //封装文件数据
        sb.append(TWO_HYPHENS).append(BOUNDARY).append(LINE_END);
        sb.append("Content-Disposition: form-data; name=\"file\"; filename=\"a.jpg\"").append(LINE_END);
        sb.append("Content-Type: file/*").append(LINE_END);
        sb.append(LINE_END);

        setBytesToOutputStream(connection.getOutputStream(), sb.toString().getBytes());

        FileInputStream fileInputStream = new FileInputStream("d:/a.jpg");
        setBytesToOutputStream(connection.getOutputStream(), fileInputStream);
        
        //写入标记结束位
        byte[] endData = (LINE_END + TWO_HYPHENS + BOUNDARY + TWO_HYPHENS + LINE_END).getBytes();
        setBytesToOutputStream(connection.getOutputStream(), endData);
        
        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            byte[] b = getBytesFromInputStream(connection.getInputStream());
            String back = new String(b);
            System.out.println("multi返回结果:" + back);
        } else {
            System.out.println("multi返回状态码:" + connection.getResponseCode());
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        connection.disconnect();
    }
}

4.3、上传文件方法变通

这种方式上传文件完全是模拟页面的提交行为来编码的,比较繁琐。可以把文件转成字符串,然后通过键值对传给服务端,服务端执行相反的过程来存储文件:

客户端:文件-> 字节数组->Base64字符串

服务端:Base64字符串-> 字节数组->文件

按照这种方式来实现应该比较容易,这里就不演示了。

5、完整例子

package com.inspur.http;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.net.URLEncoder;

/**
 * 
 * 通过HttpURLConnection调用Http接口
 *
 */
public class HttpURLConnectionCase {
    /**
     * GET请求
     */
    public static void get() {
        HttpURLConnection connection = null;
        try {
            String requestPath = "http://localhost:8080/webframe/demo/test/getUser?userId=1000&userName=" + URLEncoder.encode("李白", "utf-8");
            URL url = new URL(requestPath);
            //设置代理
            //InetSocketAddress addr = new InetSocketAddress("127.0.0.1", 8888);  
            //Proxy proxy = new Proxy(Proxy.Type.HTTP, addr);
            //connection = (HttpURLConnection)url.openConnection(proxy);
            
            connection = (HttpURLConnection)url.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                byte[] b = getBytesFromInputStream(connection.getInputStream());
                String back = new String(b);
                System.out.println("GET返回结果:" + back);
            } else {
                System.out.println("GET请求状态码:" + connection.getResponseCode());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            connection.disconnect();
        }
    }
    
    /**
     * POST请求,发送键值对数据
     */
    public static void post() {
        HttpURLConnection connection = null;
        try {
            String requestPath = "http://localhost:8080/webframe/demo/test/getUser";
            URL url = new URL(requestPath);
            connection = (HttpURLConnection)url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.connect();
            
            String param = "userId=1000&userName=李白";
            setBytesToOutputStream(connection.getOutputStream(), param.getBytes());
            
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                byte[] b = getBytesFromInputStream(connection.getInputStream());
                String back = new String(b);
                System.out.println("POST返回结果:" + back);
            } else {
                System.out.println("POST返回状态码:" + connection.getResponseCode());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            connection.disconnect();
        }
    }
    
    /**
     * POST请求,发送json格式数据
     */
    public static void post2() {
        HttpURLConnection connection = null;
        try {
            String requestPath = "http://localhost:8080/webframe/demo/test/addUser";
            URL url = new URL(requestPath);
            connection = (HttpURLConnection)url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-type", "application/json");
            connection.connect();
            
            String param = "{\"userId\": \"1001\",\"userName\":\"杜甫\"}";
            setBytesToOutputStream(connection.getOutputStream(), param.getBytes());
            
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                byte[] b = getBytesFromInputStream(connection.getInputStream());
                String back = new String(b);
                System.out.println("POST2返回结果:" + back);
            } else {
                System.out.println("POST2返回状态码:" + connection.getResponseCode());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            connection.disconnect();
        }
    }
    
    /**
     * 上传文件及发送键值对数据
     */
    public static void multi() {
        String BOUNDARY = java.util.UUID.randomUUID().toString();
        String TWO_HYPHENS = "--";
        String LINE_END = "\r\n";
        HttpURLConnection connection = null;
        try {
            String requestPath = "http://localhost:8080/webframe/demo/test/multi";
            URL url = new URL(requestPath);
            connection = (HttpURLConnection)url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setRequestProperty("Content-type", "multipart/form-data; BOUNDARY=" + BOUNDARY);
            connection.connect();
            
            StringBuffer sb = new StringBuffer();
            //封装键值对数据1
            sb.append(TWO_HYPHENS).append(BOUNDARY).append(LINE_END);
            sb.append("Content-Disposition: form-data; name=\"param1\"").append(LINE_END);
            sb.append(LINE_END);
            sb.append("参数1").append(LINE_END);
            
            //封装键值对数据2
            sb.append(TWO_HYPHENS).append(BOUNDARY).append(LINE_END);
            sb.append("Content-Disposition: form-data; name=\"param2\"").append(LINE_END);
            sb.append(LINE_END);
            sb.append("参数2").append(LINE_END);
            
            //封装文件数据
            sb.append(TWO_HYPHENS).append(BOUNDARY).append(LINE_END);
            sb.append("Content-Disposition: form-data; name=\"file\"; filename=\"a.jpg\"").append(LINE_END);
            sb.append("Content-Type: file/*").append(LINE_END);
            sb.append(LINE_END);

            setBytesToOutputStream(connection.getOutputStream(), sb.toString().getBytes());

            FileInputStream fileInputStream = new FileInputStream("d:/a.jpg");
            setBytesToOutputStream(connection.getOutputStream(), fileInputStream);
            
            //写入标记结束位
            byte[] endData = (LINE_END + TWO_HYPHENS + BOUNDARY + TWO_HYPHENS + LINE_END).getBytes();
            setBytesToOutputStream(connection.getOutputStream(), endData);
            
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                byte[] b = getBytesFromInputStream(connection.getInputStream());
                String back = new String(b);
                System.out.println("multi返回结果:" + back);
            } else {
                System.out.println("multi返回状态码:" + connection.getResponseCode());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            connection.disconnect();
        }
    }
    
    /**
     * 从输入流获取数据
     * @param in
     * @return
     * @throws IOException
     */
    private static byte[] getBytesFromInputStream(InputStream in) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] b = new byte[1024];
        int len;
        while ((len = in.read(b)) != -1) {
            baos.write(b, 0, len);
        }
        byte[] bytes = baos.toByteArray();
        baos.close();
        in.close();
        return bytes;
    }
    
    /**
     * 向输入流发送数据
     * @param out
     * @param bytes
     * @throws IOException
     */
    private static void setBytesToOutputStream(OutputStream out, byte[] bytes) throws IOException {
        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
        byte[] b = new byte[1024];
        int len;
        while ((len = bais.read(b)) != -1) {
            out.write(b, 0, len);
        }
        out.flush();
    }
    
    /**
     * 向输入流发送数据
     * @param out
     * @param bytes
     * @throws IOException
     */
    private static void setBytesToOutputStream(OutputStream out, InputStream data) throws IOException {
        byte[] b = new byte[1024];
        int len;
        while ((len = data.read(b)) != -1) {
            out.write(b, 0, len);
        }
        out.flush();
    }
    
    public static void main(String[] args) {
        get();
        post();
        post2();
        multi();
    }
}
View Code

 

 


原文链接:https://www.cnblogs.com/wuyongyin/p/11915587.html
如有疑问请与原作者联系

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:一、逻辑架构与存储引擎

下一篇:我的第一个Java博客