如何修复" 400错误请求"用java HttpClient在android上传文件?

时间:2015-07-24 19:04:56

标签: android http apache-commons-httpclient

我需要将文件上传到服务器。如果我使用" curl -i -F filedata = @" PATH TO FILE" http://█.199.166.14/audiostream"它返回200 OK代码(或者可能是这个命令不正确)。 但是当我使用java函数时

public String send()
{
    try {
        url = "http://█.199.166.14/audiostream";
        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "test.pcm");
        try {
            Log.d("transmission", "started");
            HttpClient httpclient = new DefaultHttpClient();

            HttpPost httppost = new HttpPost(url);
            ResponseHandler Rh = new BasicResponseHandler();

            InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file), -1);
            reqEntity.setContentType("binary/octet-stream");
            reqEntity.setChunked(true); // Send in multiple parts if needed
            httppost.setEntity(reqEntity);
            HttpResponse response = httpclient.execute(httppost);

            response.getEntity().getContentLength();
            StringBuilder sb = new StringBuilder();
            try {
                BufferedReader reader =
                        new BufferedReader(new InputStreamReader(response.getEntity().getContent()), 65728);
                String line = null;

                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }
            }
            catch (IOException e) { e.printStackTrace(); }
            catch (Exception e) { e.printStackTrace(); }


            Log.d("Response", sb.toString());
            Log.d("Response", "StatusLine : " + response.getStatusLine() + " Entity: " + response.getEntity()+ " Locate: " + response.getLocale() + " " + Rh);
            return sb.toString();
        } catch (Exception e) {
            // show error
            Log.d ("Error", e.toString());
            return e.toString();
        }
    }
    catch (Exception e)
    {
        Log.d ("Error", e.toString());
        return e.toString();
    }

}

它返回400 Bad请求。 我还不确定服务器是否正确上传了此文件的尝试,但我无法检查。

1 个答案:

答案 0 :(得分:0)

从收到的错误中可能出现格式错误的HTTP查询。如果audiostream是php,请写完整个链接。

此外,似乎"http://█.199.166.14/audiostream处可能存在错误/错误的编码字符,链接应为http://(IP or DNS)/(rest of URL)(the URI)

你应该删除链接,然后再手动写入。

如果这些问题没有解决问题,那么服务器(或其路径设备)可能会阻止您。从访问日志及其访问的安全规则中检查您是否被阻止(某些路由器可能阻止用户执行重复查询作为一种反“拒绝服务”措施)