Java-将文件上载到URL的post请求
我正在寻找使用POST请求将文件上传到服务器的可能性 我一直在尝试使用restTemplates,但不起作用,然后我尝试使用以下代码:Java-将文件上载到URL的post请求,java,post,file-upload,upload,Java,Post,File Upload,Upload,我正在寻找使用POST请求将文件上传到服务器的可能性 我一直在尝试使用restTemplates,但不起作用,然后我尝试使用以下代码: HttpClient httpclient = new DefaultHttpClient(); httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); String urlParam = "http://my
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
String urlParam = "http://myURL";
HttpPost httppost = new HttpPost(urlParam);
File file = new File(filename);
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file, "image/jpeg");
mpEntity.addPart("file", cbFile);
ArrayList<NameValuePair> postParameters;
postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("id_category", "0"));
postParameters.add(new BasicNameValuePair("token", "c4c533d2825f8791a07265d812d62d90"));
postParameters.add(new BasicNameValuePair("tab", "AP"));
postParameters.add(new BasicNameValuePair("action", "addImage"));
postParameters.add(new BasicNameValuePair("action", "addImage"));
postParameters.add(new BasicNameValuePair("qqfile", "IMG_0599.jpg"));
httppost.setEntity(new UrlEncodedFormEntity(postParameters));
Header headers2 = new BasicHeader("Cookie", cookieNew);
httppost.setEntity(mpEntity);
httppost.setHeader(headers2);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse responseX = httpclient.execute(httppost);
HttpEntity resEntity = responseX.getEntity();
System.out.println(responseX.getStatusLine());
if (resEntity != null) {
System.out.println(EntityUtils.toString(resEntity));
}
if (resEntity != null) {
resEntity.consumeContent();
}
httpclient.getConnectionManager().shutdown();
您知道原因以及如何避免吗?实体设置了两次
httppost.setEntity(new UrlEncodedFormEntity(postParameters)); //it is overwritten by next one
httppost.setEntity(mpEntity);
具有不同的值-因此使用最后一个。您应该向多部分实体添加参数 试试这样的方法:
HttpURLConnection conn = (HttpURLConnection) new URL("http://something").openConnection();
OutputStream outputStream = conn.getOutputStream();
// Write your object to the output stream
InputStream inputStream = conn.getInputStream();
你得到了什么样的回应?我已经更新了信息
httppost.setEntity(new UrlEncodedFormEntity(postParameters)); //it is overwritten by next one
httppost.setEntity(mpEntity);
HttpURLConnection conn = (HttpURLConnection) new URL("http://something").openConnection();
OutputStream outputStream = conn.getOutputStream();
// Write your object to the output stream
InputStream inputStream = conn.getInputStream();