【发布时间】:2013-05-04 23:44:27
【问题描述】:
我想使用 jersey API 在 java 中创建一个安静的 Web 服务并在 android 应用程序中使用它。我在 SO 上得到了this question,但它谈论的是 java 客户端,而我有 android 客户端。
我的服务如下所示:
@Path("/no")
public class CheckNumber {
@POST
@Produces("application/json")
@Consumes("application/json")
public String getDetails(@PathParam("cNo") String cNo) {
String CardNo="";
try {
JSONObject jsonObj = new JSONObject(cNo);
CardNo=jsonObj.getString("CardNo");
} catch (ParseException e1) {
e1.printStackTrace();
}
//Do something
return "someValue";
}
}
现在是客户端:
public class MainActivity extends Activity {
JSONObject json = new JSONObject();
String wsdl = "http://192.168.1.105:8080/restdemo/check/no/";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new RequestTask().execute("1234567890");
}
class RequestTask extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String add = "{\"CardNo\":\"" + uri[0] + "\"}";
HttpPost postMethod = new HttpPost(wsdl);
String responseString = null;
try {
postMethod.addHeader("Content-Type", "application/json");
HttpEntity entity = new StringEntity(add);
postMethod.setEntity(entity);
response = httpclient.execute(postMethod);
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else {
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return responseString;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}
}
我刚刚开始使用 REST Web 服务。我成功创建了一个使用字符串并返回字符串的示例休息服务,并在 android 应用程序中使用了此服务。
但是当我尝试使用 POST 方法传递 json 字符串时。它在日志中给出以下错误:
java.io.IOException: Internal Server Error
at com.example.restclient.MainActivity$RequestTask.doInBackground(MainActivity.java:85)
其中 MainActivity.java:85 是 throw new IOException(statusLine.getReasonPhrase());,这意味着 statusLine.getStatusCode() 没有返回 HttpStatus.SC_OK。相反,它返回状态码 = 500。
任何帮助表示赞赏。
【问题讨论】:
-
首先,尝试服务器日志,获取异常。服务器是否可靠地或间歇性地失败?您是否使用非 android 实现 (java/wget/curl) 重现了该错误?您是否看到通过网络传输的 HTTP 数据? (服务器上的 tcpdump -Xs1600 可能会有所帮助)
-
statusLine.getStatusCode() 没有返回 HttpStatus.SC_OK
-
也尝试了简单的 java 客户端。同样的错误。
标签: java android web-services rest ioexception