以下curl命令在java中的等价物是什么:
curl -X POST -F "file=@$File_PATH"
Run Code Online (Sandbox Code Playgroud)
我想用Java执行的请求是:
curl -X POST -F 'file=@file_path' http://localhost/files/
Run Code Online (Sandbox Code Playgroud)
我在努力:
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();
Run Code Online (Sandbox Code Playgroud)
小智 3
我昨天遇到了这个问题。这是一个使用 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()));
}
}
Run Code Online (Sandbox Code Playgroud)
根据需要设置 filePath 和 url。如果您使用的不是文件,则可以用 ByteArrayBody、InputStreamBody 或 StringBody 替换 FileBody。我的特殊情况需要 ByteArrayBody,但上面的代码适用于文件。
归档时间: |
|
查看次数: |
4102 次 |
最近记录: |