Java HttpClient 发送multipart form-data的Post请求


原文连接:https://www.jianshu.com/p/d6ab78e4ed73?tdsourcetag=s_pcqq_aiomsg

 

一、背景

我们目前正在对Jenkins进行二次开发,开源社区提供了针对jenkins的API,如:https://github.com/jenkinsci/java-client-api
但是,API支持的功能并不是很完善,如没有发现支持用户凭证的相关接口, 因此,只能通过其他解决方案来实现。

二、解决方案

2.1 curl命令行

参考文献:
https://stackoverrun.com/cn/q/8142466

2.1.1 方式一

curl -X POST 'http://user:token@jenkins_server:8080/credentials/store/system/domain/_/createCredentials' \ --data-urlencode 'json={ "": "0", "credentials": { "scope": "GLOBAL", "id": "identification", "username": "manu", "password": "bar", "description": "linda", "$class": "com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl" } }' 

2.1.2 方式二

如果方式一,报403错误,如下所示:

<body><h2>HTTP ERROR 403</h2> <p>Problem accessing /credentials/store/system/domain/_/createCredentials. Reason: <pre> No valid crumb was included in the request</pre></p><hr><i><small>Powered by Jetty://</small></i><hr/> 

可以使用下面的方式

CRUMB=$(curl -s 'http://user:token@jenkins_server:8080/crumbIssuer/api/xml?xpath=concat(//crumbRequestField,":",//crumb)') curl -H $CRUMB -X POST 'http://user:token@jenkins_server:8080/credentials/store/system/domain/_/createCredentials' \ --data-urlencode 'json={ "": "0", "credentials": { "scope": "GLOBAL", "id": "identification", "username": "manu", "password": "bar", "description": "linda", "$class": "com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl" } }' 

2.2 Postman测试工具

 

 
postman测试post

 
查看原生的发送请求方式

如何看得懂,上面的协议呢?
https://blog.csdn.net/hairetz/article/details/6047905

 

2.3 Java代码

  1. 依赖的jar包
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.4.1</version> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpcore</artifactId> <version>4.4.1</version> </dependency> 
  1. 代码如下:
public static void createUserCre(String id) { String url = "http://admin:11a8ff57440f35baead7a3cc8a21ec2c44@172.16.91.121:8888/jenkins/credentials/store/system/domain/_/createCredentials?"; HttpPost httpPost = new HttpPost(url); CloseableHttpClient client = HttpClients.createDefault(); String respContent = null; JSONObject jsonParam = new JSONObject(); JSONObject credentialsJsonParam = new JSONObject(); credentialsJsonParam.put("scope", "GLOBAL"); //注意,如果ID一样的话,插入失败 credentialsJsonParam.put("id", id); credentialsJsonParam.put("username", "abc520"); credentialsJsonParam.put("password", "123456"); credentialsJsonParam.put("description", "hello world jenkins hellow"); credentialsJsonParam.put("$class", "com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl"); jsonParam.put("credentials", credentialsJsonParam); jsonParam.put("", "0"); logger.info("=============:\t" + jsonParam.toString()); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody("json", jsonParam.toString(), ContentType.MULTIPART_FORM_DATA); HttpEntity multipart = builder.build(); HttpResponse resp = null; try { httpPost.setEntity(multipart); resp = client.execute(httpPost); //注意,返回的结果的状态码是302,非200 if (resp.getStatusLine().getStatusCode() == 302) { HttpEntity he = resp.getEntity(); logger.info("----------------123----------666666---"); respContent = EntityUtils.toString(he, "UTF-8"); } } catch (Exception e) { logger.error(e.getMessage()); } logger.info("=========================:\t" + respContent); logger.info("=========================:\t" + resp.getStatusLine().getStatusCode()); } 

开发时,可以根据自己的实际情况,进行调整。

三、补充

3.1 Java HttpClient 发送multipart/form-data带有Json文件的Post请求

说明:发送multipart/form-data带有Json文件的Post请求,文件内容其实就是json字符串,这种请求之前都是通过postman发的,见postman截图

 
postman form-data json文件1

 
postman form-data json文件2

依赖的jar包 : httpclient-4.5.3.jar,httpmime-4.3.jar

 

  1. 代码:
import java.io.File; import java.io.FileInputStream; import java.io.IOException; import org.apache.http.HttpEntity; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; public class HttpMultipartFormdataDemo1 { public static void main(String[] args) throws ClientProtocolException, IOException { // 文件sTestsetFile:solr_etl_agent35.json是存有JSON字符串的文件 String sTestsetFile=System.getProperty("user.dir")+File.separator+"testdata"+File.separator+"solr_etl_agent35.json"; String sURL="http://172.16.101.46:14401/editorialincre"; CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost uploadFile = new HttpPost(sURL); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addTextBody("field1", "yes", ContentType.TEXT_PLAIN); // 把文件加到HTTP的post请求中 File f = new File(sTestsetFile); builder.addBinaryBody( "file", new FileInputStream(f), ContentType.APPLICATION_OCTET_STREAM, f.getName() ); HttpEntity multipart = builder.build(); uploadFile.setEntity(multipart); CloseableHttpResponse response = httpClient.execute(uploadFile); HttpEntity responseEntity = response.getEntity(); String sResponse=EntityUtils.toString(responseEntity, "UTF-8"); System.out.println("Post 返回结果"+sResponse); } } 

3.2 java实现http post通讯 并进行urlencode,编码方式utf-8

  1. 通讯实现
package com.token; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; public class HttpClientUtil { /** * 日志对象 */ private static final Logger LOGGER = LoggerFactory.getLogger(HttpClientUtil.class); private HttpClientUtil(){ } public static String doPost(String url, Map<String, String> param) { // 创建Httpclient对象 CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = null; String resultString = ""; try { // 创建Http Post请求 HttpPost httpPost = new HttpPost(url); // 创建参数列表 if (param != null) { List<NameValuePair> paramList = new ArrayList<>(); for (String key : param.keySet()) { paramList.add(new BasicNameValuePair(key, param.get(key))); } // 模拟表单 UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList,"utf-8"); httpPost.setEntity(entity); } // 执行http请求 response = httpClient.execute(httpPost); resultString = EntityUtils.toString(response.getEntity(), "utf-8"); } catch (Exception e) { e.printStackTrace(); } finally { try { response.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return resultString; } } 
  1. 发起通讯
 Map<String, String> paramMap = new HashMap(); paramMap.put("name","zhangsan"); paramMap.put("age","12"); String result = HttpClientUtil.doPost("http://127.0.0.1/api?", paramMap); 

返回的result为json串

参考文献:
https://blog.csdn.net/vvv_110/article/details/85231290
https://blog.csdn.net/achang21/article/details/79304276


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM