2016-01-08 61 views
2

在Android中,如何将二进制文件上传到服务器似乎非常混乱,因为一些图书馆已经过时,而且缺乏现在应该使用的方法。 任何人都可以给如何上传二进制文件或任何文件到Android的服务器的指针?上传Android中的文件

我不想使用任何依赖关系,除非他们真的需要。

+0

尝试翻新它对于任何类型的服务器交互都非常有帮助! – Joh

回答

1

在信息缺乏什么样的服务器,这可能是,我发现this

OkHttpClient client = new OkHttpClient(); 
OutputStream out = null; 
try { 
    URL url = new URL("http://www.example.com"); 
    HttpURLConnection connection = client.open(url); 
    for (Map.Entry<String, String> entry : multipart.getHeaders().entrySet()) { 
     connection.addRequestProperty(entry.getKey(), entry.getValue()); 
    } 
    connection.setRequestMethod("POST"); 
    // Write the request. 
    out = connection.getOutputStream(); 
    multipart.writeBodyTo(out); 
    out.close(); 

    // Read the response. 
    if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) { 
     throw new IOException("Unexpected HTTP response: " 
       + connection.getResponseCode() + " " + connection.getResponseMessage()); 
    } 
} 
finally { 
    try { if (out != null) out.close(); } 
    catch (Exception e) {} 
} 

我认为你提到的弃用/过时的库将ApacheHttpClient,因此,我建议OkHttp(即使用HttpUrlConnection我相信)。

要添加OkHttp如扶养您可以编辑build.gradle,如:

dependencies { 
    //some other dependencies 
    compile 'com.squareup.okhttp:okhttp:2.7.2' 
} 

可用版本可以在这里找到:mvnrepository(无需手动下载,只需添加它们像上面,gradle这个会下载它们本身)

+0

我应该使用哪些依赖项以及如何添加它们? –

+0

我更新了我的答案 – sschrass

+0

嘿,看起来“客户端”没有叫做“open()”的方法。 –