gpt4 book ai didi

android - 如何使用于在 ASP.NET Web API 中创建自定义异常的字符串在 Android 中被解释为 HttpURLConnection.getResponseMessage ()

转载 作者:行者123 更新时间:2023-11-30 02:34:23 24 4
gpt4 key购买 nike

我正在尝试从 ASP.NET Web API 发送自定义异常,但是当我从 Android 使用这些 WebService 时,我总是收到不同的消息:

这是我在 Android 中读取网络服务的方式:

public Object doRequest(String url) {       
String charset = Charset.defaultCharset().displayName();
try {
if (mFormBody != null) {
// Form data to post
mConnection
.setRequestProperty("Content-Type",
"application/json; charset="
+ charset);
mConnection.setFixedLengthStreamingMode(mFormBody.length());
}
mConnection.connect();

if (mFormBody != null) {
OutputStream out = mConnection.getOutputStream();
writeFormData(charset, out);
}

// Get response data
int status = mConnection.getResponseCode();
if (status >= 300) {
String message = mConnection.getResponseMessage();
return new HttpResponseException(status, message);
}

InputStream in = mConnection.getInputStream();
String enconding = mConnection.getContentEncoding();
if (enconding == null) {
enconding = "UTF-8";
}
BufferedReader reader = new BufferedReader(new InputStreamReader(
in, enconding));

StringBuilder sb = new StringBuilder();

String line=null;
while ((line=reader.readLine()) != null) {
sb.append(line);
}

return sb.toString().trim();

} catch (Exception e) {
return e;
}
finally{
if(mConnection!=null){
mConnection.disconnect();
}
}
}

如您所见,我检查了 getResponseCode() 返回的值,如果它等于或大于 300,我将抛出异常。一切正常,除了 getResponseMessage() 没有返回我在 WebApi 中创建异常时使用的字符串。相反,我收到此错误:

enter image description here

在 WebApi 中,我在 catch block 中所做的就是抛出异常:

    try
{

}
catch (Exception ex)
{
throw ex;
}

使用 fiddler 意识到我收到了这条消息:

{"Message":"Error."}

好吧,在网上寻找解决方案,我发现我可以这样做:

try
{

}
catch (Exception ex)
{

throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, ex.Message));
//throw (ex);
}

但不幸的是,这也不起作用。尽管 fiddler 现在显示了我用来创建异常的消息。

enter image description here当我读取 getResponseMessage() 的值时返回此字符串:"Not Found".

你知道我需要做什么才能让 WebApi 通过 Exception 发送的消息到达 Android,特别是 getResponseMessage()属性(property)?

提前致谢。

最佳答案

嗯,我想你需要创建一个 HttpResponseMessage首先对象,然后基于该对象创建您要抛出的 HttpResponseException

设置 HttpResponseMessage 对象非常简单。大多数时候,您只需要设置两个属性:ContentReasonPhrase

            try
{

}
catch (Exception ex)
{

HttpResponseMessage msg = new HttpResponseMessage(HttpStatusCode.NotFound)
{
Content = new StringContent(string.Format("Excepción")),
ReasonPhrase = ex.Message
};
throw new HttpResponseException(msg);
}

如您所见,ReasonPhrase 是我们传递异常消息的地方。

希望对您有所帮助。

关于android - 如何使用于在 ASP.NET Web API 中创建自定义异常的字符串在 Android 中被解释为 HttpURLConnection.getResponseMessage (),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26835211/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com