httpclient的post请求模板使用

pom依赖

<!--        httpclient,fastjson-->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.4.13</version>
        </dependency>

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.12</version>
        </dependency>

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.5.13</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.74</version>
        </dependency>
public static String getToken(){
String httpUrl="";
try{
CloiseableHttpClient httpClient=HttpClients.CreateDefault();
HttpPost httpPost = new HttpPost(httpUrl);

//这里设置请求头部
httpPost.setHeader("name","value");

String AppId= new StringBody("value",ContentType.Text_PLAIN);

//这是设置传参内容,模拟postman请求的form-data数据请求
HttpEntity httpEntity = MultipartEntityBuilder.create()
.addPart("name",AppId)//添加text内容
.addBinaryBody("name",inputStream,ContentType.APPLICATION_OCTET_STREAM,fileName)//添加file内容
.build();

httpPost.setEntity(httpEntity);

CloseableHttpResponse response = httpClient.execute(httpPost);
HttpEntity entity=response.getEntity();

String responseContent=EntityUtils.toString(entity,"utf-8");

//通过alibaba的fastjson解析数据即可
}catch(Exception e){
e.printStackTrace();
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容