httpclient的post请求模板使用

pom依赖


        
            org.apache.httpcomponents
            httpcore
            4.4.13
        

        
            org.apache.httpcomponents
            httpclient
            4.5.12
        

        
            org.apache.httpcomponents
            httpmime
            4.5.13
        

        
            com.alibaba
            fastjson
            1.2.74
        
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();
}

你可能感兴趣的:(httpclient的post请求模板使用)