2014-04-18 105 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,因此没有输出(请求主体)发送。