我需要使用post方法将图像文件上传到http服务器。 我的代码在这里
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
InputStreamEntity reqEntity = new InputStreamEntity(
new FileInputStream(file), -1);
reqEntity.setContentType("binary/octet-stream");
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
//Do something with response...
} catch (Exception e) {
// show error
}
它不起作用。以正确的方式提出我的意见。
注意:服务器是IIS服务器。
答案 0 :(得分:0)
您可以尝试reqEntity.setChunked(true);
如果需要,可以发送多个部分
为此你的代码应该是
InputStreamEntity reqEntity = new InputStreamEntity(
new FileInputStream(file), -1);
reqEntity.setContentType("binary/octet-stream");
reqEntity.setChunked(true);
httppost.setEntity(reqEntity);
但如果您的文件大小,那么您应该使用
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
File f = new File(file);
FileInputStream fileInputStream = new FileInputStream(f);
InputStreamEntity reqEntity = new InputStreamEntity(fileInputStream, f.length());
httppost.setEntity(reqEntity);
reqEntity.setContentType("binary/octet-stream");
HttpResponse response = httpclient.execute(httppost);
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
responseEntity.consumeContent();
}
httpclient.getConnectionManager().shutdown();
答案 1 :(得分:0)
前几天我也被困在这一点上,无法正常工作。我正在使用WCF休息服务并花费15-20天。最后我将我的WCF更改为webservice,现在我可以非常轻松地上传图像和调用服务。我使用SOAP对象将其称为
private String RegisterUser(String[] parameter, String image) {
SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE,
OPERATION_NAME);
request.addProperty("param1", parameter[0].toString());
request.addProperty("param2", parameter[1].toString());
request.addProperty("profilepic", image);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS);
Object response = null;
try {
httpTransport.call(SOAP_ACTION + OPERATION_NAME, envelope);
response = envelope.getResponse();
} catch (Exception exception) {
response = exception.toString();
}
return response.toString();
}
我已将Image转换为字符串,然后调用webservice,一切都非常流畅。
如果愿意使用webservice,你可以试试。希望这会对你有所帮助
的问候,
Sourabh