2016-03-15 217 views
0

我想爲上傳文件到服務器發出「PUT」請求。 對於這個我使用HttpURLConnection的,但它不是working.I給下面HttpURLConnection方法setDoOutput()在設置true後也總是返回false

public static String sendFileToServer(String filePath, String targetUrl) 
{ 
    URL url = new URL(targetUrl); 
    HttpURLConnection connection = (HttpURLConnection) url.openConnection(); 
    connection.setDoOutput(true); 
    connection.setInstanceFollowRedirects(false); 
    connection.setRequestMethod("PUT"); 
    connection.setUseCaches(false); 
    connection.setRequestProperty("Connection", "Keep-Alive"); 
    connection.setRequestProperty("Cache-Control", "no-cache"); 

} 

這是我的代碼的代碼,但連接方法我得到的是

doOutput = false 

method = {[email protected]} "GET" 

我試圖解決,但它無法正常工作。請幫助

回答

0

關注這個exsample:

private void openConnection(HttpURLConnection connection, HttpRequest request) throws IOException { 
    if (request.getHttpBody() != null) { 
     connection.setDoOutput(true); 
    } 
    connection.setRequestMethod(request.getMethod()); 
    Map<String, String> map = request.getHeaders(); 
    for (Map.Entry<String, String> entry : map.entrySet()) { 
     String key = entry.getKey(); 
     String value = entry.getValue(); 

     Logger.i("prepare headers with key = " + key + " value = " + value); 
     connection.setRequestProperty(entry.getKey(), entry.getValue()); 
    } 
    connection.setReadTimeout((int) mReadTimeout); 
    connection.setConnectTimeout((int) mConnectionTimeout); 
    if (connection.getDoOutput()) { 
     connection.connect(); 
    } 
} 

的HttpRequest - 自定義包裝類頭。

+0

HttpRequest方法不可用 – Aayushi

+0

HttpRequest - 具有標頭的自定義包裝類。 –

+0

好吧,會嘗試 – Aayushi