【问题标题】:How to fix "400 bad request" with uploading file on android with java HttpClient?如何使用 java HttpClient 在 android 上上传文件来修复“400 bad request”?
【发布时间】:2015-07-24 19:04:56
【问题描述】:

我需要上传一个文件到服务器。如果我使用“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 错误请求。 我也不确定服务器是否正确地继续我尝试上传此文件,但我无法检查它。

【问题讨论】:

标签: android http apache-commons-httpclient


【解决方案1】:

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

另外,"http://█.199.166.14/audiostream 似乎有错误/错误的编码字符,链接应该是http://(IP or DNS)/(rest of URL)(the URI)

您应该删除链接,然后手动重新写入。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-19
    • 1970-01-01
    • 2022-11-29
    • 2019-12-24
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多