java httppost上传文件
时间: 2023-09-01 16:12:47 浏览: 129
好的,以下是Java使用HttpPost上传文件的示例代码:
```java
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class HttpPostUploadFileExample {
public static void main(String[] args) {
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://example.com/upload");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addPart("file", new FileBody(new File("/path/to/file")));
httpPost.setEntity(builder.build());
try {
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity, "UTF-8");
System.out.println(responseString);
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
其中,`http://example.com/upload` 是上传文件的接口地址,`/path/to/file` 是要上传的文件路径。在这个示例中,使用了 Apache HttpClient 和 Apache HttpCore 库,需要导入相应的依赖。
阅读全文