2014-04-18 33 views
0

我對Android開發非常陌生,所以如果我的嘗試不是100%正確的話,那麼很抱歉。來自Android的REST服務:400例外

在JavaScript中,我有一個連接到WCF服務的函數,它具有基本認證功能,可以爲請求的PDF文檔檢索base64編碼的字符串。在JavaScript中,下面的工作:

function svcPost(param) { 
    return jQuery.ajax({ 
     type: 'POST', 
     url: 'https://url-to-service.svc/' + param.method, 
     contentType: 'application/json; charset=utf-8', 
     dataType: 'json', 
     data: JSON.stringify(param.json), 
     async: true, 
     processData: true, 
     crossDomain: true, 
     beforeSend: function (request) { 
      request.setRequestHeader("Authorization", "Basic " + window.localStorage.getItem('credentials')); 
     }, 
     success: function(result) { 
      return result; 
     }, 
     error: function (xhr, status, error) { 
      return error; 
     } 
    }); 
}; 

那麼該功能將被稱爲中承諾要恢復上述base64編碼字符串:

jQuery.when(
     svcPost({ method: 'GetBase64Pdf', json: { id: lookupId } }) 
    ) 
    .done(function (result) { 
     deferred.resolve(result[0]); 
    }) 
    .fail(function(error) { 
     console.error(error); 
    }); 

我想在Android應用程序複製這一點,我沒有運氣。每次對該服務的調用都會返回一個400 BAD REQUEST,並聲明該調用期望使用'value'的'type',但發現爲空。

我知道這與'dataType:'json''有關,但我似乎無法在Android中使用此工作。

的代碼,我到目前爲止有:

byte[] bytes = "Username:Password1".getBytes("UTF-8"); 
String encoded = Base64.encodeToString(bytes, 0); 
String itemid = Integer.toString(lookupId); 

String param = "id=" + URLEncoder.encode(itemid, "UTF-8"); 
String url = "https://url-to-service.svc/GetBase64Pdf"; 

URL uri = new URL(url); 
HttpURLConnection connection = (HttpURLConnection)uri.openConnection(); 

try { 
    connection.setRequestMethod("POST");       
connection.setRequestProperty("Content-Type", "application/json; charset=utf-8"); 
connection.setRequestProperty("Content-Length", Integer.toString(param.getBytes().length)); 
connection.setRequestProperty("Accept", "application/json"); 
connection.setRequestProperty("Authorization", "Basic " + encoded);  

connection.setDoOutput(false); 
connection.setUseCaches(false); 
connection.setDoInput(true); 

DataOutputStream wr = new DataOutputStream(connection.getOutputStream()); 
wr.writeBytes(param); 
wr.flush(); 
wr.close(); 

InputStream in = null; 

int status = connection.getResponseCode(); 

if (status >= HttpStatus.SC_BAD_REQUEST) { 
    in = connection.getErrorStream(); 
} 
else { 
    in = connection.getInputStream(); 
} 

BufferedReader rd = new BufferedReader(new InputStreamReader(in)); 
String line; 
StringBuffer response = new StringBuffer(); 

while ((line = rd.readLine()) != null) { 
    response.append(line); 
    response.append('\r'); 
} 

rd.close(); 

我已經嘗試添加「接受」作爲「數據類型:‘標頭條JSON’」但是,這並不工作。

如果我添加「&類型= JSON」與參數字符串,它返回錯誤消息作爲JSON陣列。

有什麼想法嗎?我無權訪問WCF服務,它是客戶端環境中的第三方調用,所以我無法檢查服務本身。 JavaScript的工作原理,但我不能在Android中複製JavaScript實現。

任何幫助將不勝感激,我一直在這個撕裂了幾個小時的沒有博客,我讀過有過任何成功:(

回答

0

您需要設置則將DoOutput爲true:

connection.setDoOutput(true); 

您正在設置爲false,因此沒有輸出(請求主體)發送。