0

我是http文件传输的新手。我想将文件从 android sdcard 发送到服务器。为此,我尝试了以下代码。我将字节转换为 json 字符串并将其发送到服务器。但我无法在服务器端接收它。我在服务器端使用jsp。但是应该有一些有效的方法来做到这一点。请给我一些想法。

 HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://10.0.2.2:8084/httptest");

    try {
        // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        String encodedString = convertURL(jsonString);
        nameValuePairs.add(new BasicNameValuePair("wavfil", encodedString));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        if (entity != null) {

            String responseString = EntityUtils.toString(entity, "UTF-8"); 
            Toast.makeText(this, responseString, Toast.LENGTH_SHORT).show();
            tv.setText(responseString);
            Log.d("HTTP LOG", responseString);

        }
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }

jsp

<%

String value = request.getParameter("wavfil");

byte[] wavByte = value.getBytes();

FileOutputStream fos = new FileOutputStream("/TESTFILE.wav");
fos.write(wavByte, 0, wavByte.length);
if (wavByte != null) {
    out.println("Success");
} else {
    out.println("Failed");
}

%>

4

1 回答 1

1

添加以下行

HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://10.x.x.x:8084/httptest");

try {
    // Add your data
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
    String encodedString = convertURL(jsonString);
    nameValuePairs.add(new BasicNameValuePair("wavfil", encodedString));
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Create and attach file to the Post
File file = new File("pathto your file"); //replace with actual path
MultipartEntity entity = new MultipartEntity();

httppost.setEntity(entity);

    // Execute HTTP Post Request
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();
    entity.addPart("file", new FileBody(file));
    if (entity != null) {

        String responseString = EntityUtils.toString(entity, "UTF-8"); 
        Toast.makeText(this, responseString, Toast.LENGTH_SHORT).show();
        tv.setText(responseString);
        Log.d("HTTP LOG", responseString);

    }
} catch (ClientProtocolException e) {
    // TODO Auto-generated catch block
} catch (IOException e) {
    // TODO Auto-generated catch block
}
于 2013-01-31T06:18:24.300 回答