0

我有一个网络服务,它获取音频并对其进行一些操作,最后返回一个字符串,这个网络服务有一个像这样的网页

<form name="form1" method="post" action="Default.aspx" id="form1" enctype="multipart/form-data">

<input type="file" name="FileUpload3" id="FileUpload3" style="width:325px;" />
<input type="submit" name="Button6" value="Upload File" id="Button6" />   
<span id="Label1"></span>

</form>

当为uploadfile3选择文件并按上传文件时,应重新加载同一页面,然后在跨度标签中显示字符串,我想通过android连接此Web服务,所以我尝试使用以下代码连接和上传文件,服务器响应200代码但是没有文件上传到服务器并且没有字符串显示,似乎服务器在没有选择文件的情况下按下上传文件,我该怎么办?请帮忙。

public void upLoad2Server() throws ClientProtocolException, IOException {

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://11.12.13.174/file_transfer_sample/ClientWebSite/Default.aspx");

    File file = new File(Environment.getExternalStorageDirectory().getPath() + "/test.wav");
    ContentBody cbFile = new FileBody(file, "audio/wav"); 
    MultipartEntity reqEntity = new MultipartEntity();
    reqEntity.addPart("FileUpload3", cbFile);
    httppost.setEntity(reqEntity);  
    HttpResponse response = httpclient.execute(httppost);
    Log.i("status", String.valueOf(response.getStatusLine()));
}
4

2 回答 2

0

检查此代码以将文件从 Android 上传到 Web 服务器

public class UploadFileToServer extends AsyncTask<Object, String, Object>
{
URL connectURL;
String params;
String responseString;
String fileName;
byte[] dataToServer;
FileInputStream fileInputStream;
private int serverResponseCode;

private String serverResponseMessage;

private static final String TAG = "Uploader";


public void setUrlAndFile(String urlString, File fileName)
{
    Log.d(TAG,"StartUploader");

    try
    {
        fileInputStream = new FileInputStream(fileName);
        connectURL = new URL(urlString);
    }
    catch(Exception e)
    {
        e.getStackTrace();
        publishProgress(e.toString());

    }
    this.fileName = fileName.getAbsolutePath()+".txt";

}

synchronized void doUpload()
{
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary = "*****";
    Log.d(TAG,"lv1");

    try
    {
        Log.d(TAG,"doUpload");
        publishProgress("Uploading...");

        HttpURLConnection conn = (HttpURLConnection)connectURL.openConnection();
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection","Keep-Alive");
        conn.setRequestProperty("Content-Type","multipart/form-data;boundary=" + boundary);
        DataOutputStream dos  = new DataOutputStream(conn.getOutputStream());
        dos.writeBytes(twoHyphens + boundary + lineEnd);
        dos.writeBytes("Content-Disposition:form-data; name=\"Uploaded\";filename=\"" + fileName + "\"" + lineEnd);
        dos.writeBytes(lineEnd);

        Log.d(TAG,"LvA");
        Log.d(TAG,twoHyphens + boundary + lineEnd + ";Content-Disposition:form-data; name=\"Uploaded\";filename=\"" + fileName + "\"" + lineEnd);

        int bytesAvailable = fileInputStream.available();

        int maxBufferSize = 1024;
        int bufferSize = Math.min(bytesAvailable, maxBufferSize);

        byte[] buffer = new byte[bufferSize];

        int bytesRead = fileInputStream.read(buffer,0, bufferSize);
        Log.d(TAG,"LvB");
        while(bytesRead > 0)
        {

            dos.write(buffer, 0, bufferSize);
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        }

        dos.writeBytes(lineEnd);
        dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

        fileInputStream.close();
       dos.flush();

        InputStream is = conn.getInputStream();
        int ch;
        Log.d(TAG,"LvC");
        StringBuffer buff = new StringBuffer();
        while((ch=is.read()) != -1)
        {
            buff.append((char)ch);
        }
       // publishProgress(buff.toString());
        dos.close();


     // Responses from the server (code and message)
        serverResponseCode = conn.getResponseCode();
        serverResponseMessage = conn.getResponseMessage();
       // Log.d(TAG,"Buffer "+buff.toString());

        Log.d(TAG,"Server Response "+serverResponseMessage);
    }

    catch(Exception e)
    {
        e.getStackTrace();
       publishProgress(e.toString());
    }
}

@Override
protected Object doInBackground(Object... arg0) 
{
    Log.d(TAG,"lv1a");
    doUpload();
    Log.d(TAG,"Uploading Completed! Path: "+connectURL);

    return null;
}

protected void onProgressUpdate(String... progress)
{
    //this.info.setText(progress[0]);
    Log.d("Progress", progress[0]);
}


}

谢谢

于 2013-11-05T13:12:51.850 回答
0

检查此代码。它将文件上传到 .NET httphandler 服务器。它使用 SSL 自签名安全性,但它是如何使用方法和多部分实体的示例。这个对我有用。

public static void main(String[] args) throws IOException {
    try {
         File f = new File(
                "c:\\eula.1028.txt");

         System.out.println("LENGTH " + f.length());        
         PostMethod method = new PostMethod("/Handler");            
         FilePart filePart = new FilePart("file",f);
         filePart.setContentType("application/pdf");
         Part[] parts = {filePart};
         MultipartRequestEntity request = new
         MultipartRequestEntity(parts, method.getParams());
         method.setRequestEntity(request);

        Protocol easyhttps = new Protocol("https",
                new EasySSLProtocolSocketFactory(), 2000);
        org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient();
        client.getHostConfiguration().setHost("localhost", 2000, easyhttps);

        client.executeMethod(method);
        String s = method.getResponseBodyAsString();
        System.out.println(s);
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}
于 2013-11-05T13:19:14.003 回答