首页 > 其他分享 >day9记录_idea上传文件接口调用

day9记录_idea上传文件接口调用

时间:2023-03-24 15:34:59浏览次数:35  
标签:multipartPostMethod day9 idea commons org import 上传 httpClient

day9_idea上传文件接口调用,如下图,调用成功

注:pom文件需要增加以下代码:

<dependencies>
        <dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
            <version>6.14.1</version>
        </dependency>

    <dependency>
        <groupId>com.jayway.jsonpath</groupId>
        <artifactId>json-path</artifactId>
        <version>2.4.0</version>
    </dependency>
    <dependency>
        <groupId>commons-httpclient</groupId>
        <artifactId>commons-httpclient</artifactId>
        <version>3.1</version>
    </dependency>
    </dependencies>

上图源码:

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.MultipartPostMethod;
import org.testng.Assert;
import org.testng.annotations.Test;


import java.io.File;
import java.io.FileNotFoundException;

public class TestApi {
    @Test
    public void testUpload(){
        try {
            String url="http://localhost:8090/fileUpload";
            //声明客户端
            HttpClient httpClient=new HttpClient();
            //设置编码格式
            httpClient.getParams().setContentCharset("UTF-8");
            //设置客户端超时
            httpClient.getParams().setConnectionManagerTimeout(5000);
            //设置读取数据超时
            httpClient.getParams().setSoTimeout(60*1000);
            //声明请求方法,下面的有删除线,因为版本不一致导致,但不影响
            MultipartPostMethod multipartPostMethod=new MultipartPostMethod(url);
            //添加上传的文件(请求参数)
            multipartPostMethod.addParameter("file",new File("E:\\bizhi.jpg"));
            //添加请求类型
            multipartPostMethod.addRequestHeader("Content-Type","multipart/form-data");
            //模拟客户端调用上传文件方法
            int code = httpClient.executeMethod(multipartPostMethod);
            //获取请求的报文
            String response=multipartPostMethod.getResponseBodyAsString();
            System.out.println(code+"\n"+response);
            Assert.assertEquals(code,200);
            Assert.assertTrue(response.contains("上传文件成功"));
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

 

标签:multipartPostMethod,day9,idea,commons,org,import,上传,httpClient
From: https://www.cnblogs.com/Y-1024/p/17213871.html

相关文章