• 大小: 4KB
    文件类型: .java
    金币: 1
    下载: 0 次
    发布日期: 2021-06-08
  • 语言: Java
  • 标签: java调用  

资源简介

java调用HTTP接口(Get请求和Post请求)

资源截图

代码片段和文件信息

package com.company;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * 功能简述:
 *
 * @author caidingnu
 * @create 2019/03/27 13:46
 * @since 1.0.0
 */
public class HTTP_Request {
    private static void httpURLGETCase() {
        String methodUrl = “http://127.0.0.1:8099/select_by_id?userid=1“;
        HttpURLConnection connection = null;
        BufferedReader reader = null;
        String line = null;
        try {
            URL url = new URL(methodUrl);
            connection = (HttpURLConnection) url.openConnection();// 根据URL生成HttpURLConnection
            connection.setRequestMethod(“GET“);// 默认GET请求
            connection.connect();// 建立TCP连接
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                reader = new BufferedReader(new InputStreamReader(connection.getInputStream() “UTF-8“));// 发送http请求
                StringBuilder result = new StringBuilder();
                // 循环读取流
                while ((line = reader.readLine()) != null) {
                    result.append(line).append(System.getProperty(“line.separator“));// “\n“
                }
                System.out.println(result.toString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            connection.disconnect();
        }
    }






//Post请求
private static void httpURLPOSTCase() {
    String methodUrl = “http://127.0.0.1:8099/select_by_id?userid=1“;
    HttpURLConnection connection = null;
    OutputStream dataout = null;
    BufferedReader reader = null;
    String line = null;
    try {
        URL url = new URL(methodUrl);
        connection = (HttpURLConnection) url.openConnection();// 根据URL生成HttpURLConnection
        connection

评论

共有 条评论