curl -X POST -F "file=@$file_PATH"
我想用Java执行的请求是:
curl -X POST -F 'file=@file_path' http://localhost/files/
我在努力:
httpClIEnt httpClIEnt = new DefaulthttpClIEnt(); httpPost httpPost = new httpPost(_URL); file file = new file(PATH); multipartentity mpEntity = new multipartentity(); Contentbody cbfile = new fileBody(file,"bin"); mpEntity.addPart("userfile",cbfile); httpPost.setEntity(mpEntity); httpResponse response = httpClIEnt.execute(httpPost); inputStream instream = response.getEntity().getContent();解决方法 我昨天碰到了这个问题.这是一个使用Apache http库的解决方案.
package curldashf;import java.io.file;import java.io.IOException;import org.apache.commons.io.fileUtils;import org.apache.http.httpResponse;import org.apache.http.clIEnt.ClIEntProtocolException;import org.apache.http.clIEnt.fluent.Request;import org.apache.http.entity.mime.multipartentity;import org.apache.http.entity.mime.content.ByteArrayBody;import org.apache.http.util.EntityUtils;public class CurlDashF{ public static voID main(String[] args) throws ClIEntProtocolException,IOException { String filePath = "file_path"; String url = "http://localhost/files"; file file = new file(filePath); multipartentity entity = new multipartentity(); entity.addPart("file",new fileBody(file)); httpResponse returnResponse = Request.Post(url) .body(entity) .execute().returnResponse(); System.out.println("Response status: " + returnResponse.getStatusline().getStatusCode()); System.out.println(EntityUtils.toString(returnResponse.getEntity())); }}
根据需要设置filePath和url.如果您使用的是文件以外的其他内容,则可以使用ByteArrayBody,inputStreamBody或StringBody替换fileBody.我的特殊情况需要ByteArrayBody,但上面的代码适用于文件.
总结以上是内存溢出为你收集整理的“Curl -F”Java等价物全部内容,希望文章能够帮你解决“Curl -F”Java等价物所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)