这是我向 url 发送 HTTP post 的代码
public static String post(String url, List<BasicNameValuePair> postvalues) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
if ( (postvalues==null) ){
postvalues= new ArrayList<BasicNameValuePair>();
}
httppost.setEntity(new UrlEncodedFormEntity(postvalues, "UTF-8"));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
return requestToString(response);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
我还想在帖子中添加一个文件(不是最后一个 byte[],只需将文件发布到 PHP $_FILES 字段即可。
我该怎么做?
谢谢
最佳答案
听起来您想发送一个多部分请求。这假设您可以在服务器端处理这样的请求:
HttpParams params = new BasicHttpParams();
for(BasicNameValuePair postValue: postValues) {
params.setParameter(postValue.getName(), postValue.getValue());
}
HttpPost post = new HttpPost();
post.setParams(params);
MultipartEntity entity = new MultipartEntity();
entity.addPart("file", new FileBody(new File(myFile)));
post.setEntity(entity);
除了将名称-值对作为参数发送之外,您还可以像现在一样创建一个 UrlEncodedFormEntity
实体,并将其作为一个单独的部分添加到多部分实体中。
关于java - 将文件(和更多值)发布到 java 中的 http 请求中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9241490/