0

我需要使用 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 服务器。

4

2 回答 2

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();
于 2013-07-13T12:21:48.613 回答
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();
    }

我已将我的图像转换为字符串,然后调用 web 服务,一切都非常顺利。

愿意使用webservice的可以试试。希望对你有帮助

问候,
苏拉布

于 2013-07-13T18:11:18.807 回答