我想再次问我的问题。我正在开发一个可以从 Android 访问的宁静 Web 服务,但自 2 周以来我遇到了一个问题。我想编写一个服务,它从数据库中获取一些字节数组并将这些写入一个文件,以便我可以从 android 使用这个服务。使用 Android,我想获取此文件,然后使用此字节绘制图形。
请给我一些提示好吗!!
谢谢
我想再次问我的问题。我正在开发一个可以从 Android 访问的宁静 Web 服务,但自 2 周以来我遇到了一个问题。我想编写一个服务,它从数据库中获取一些字节数组并将这些写入一个文件,以便我可以从 android 使用这个服务。使用 Android,我想获取此文件,然后使用此字节绘制图形。
请给我一些提示好吗!!
谢谢
在您的情况下,Web API 是一个不错的选择,因为使用它非常简单,您只需要发送一个简单的流。然后在您的应用程序中创建自己的 RestClient 以使用 Web 服务,这里有一些使用 HttpClient 的代码来做这:
public void executeRequest(HttpUriRequest request, String url) {
HttpClient client = new DefaultHttpClient();
HttpResponse httpResponse;
try{
httpResponse = client.execute(request);
responseCode = httpResponse.getStatusLine().getStatusCode();
HttpEntity entity = httpResponse.getEntity();
if (entity != null)
{
InputStream in = entity.getContent();
response = convertStreamToString(in);
in.close();
}
} catch (ClientProtocolException e) {
client.getConnectionManager().shutdown();
e.printStackTrace();
} catch (IOException e) {
client.getConnectionManager().shutdown();
e.printStackTrace();
}
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
有了这个,您可以传递一个 GET 请求以获取您需要的数据,如果您需要向查询字符串添加一些额外的参数,这也应该很好:
public void Execute(RequestMethod method) throws Exception
{
String combinedParams = "";
if (!params.isEmpty())
{
combinedParams += "?";
for (NameValuePair p : params)
{
String paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(),"UTF-8");
if (combinedParams.length() > 1)
combinedParams += "&" + paramString;
else
combinedParams += paramString;
}
}
HttpGet request = new HttpGet(url + combinedParams);
for (NameValuePair h : headers)
request.addHeader(h.getName(),h.getValue());
executeRequest(request, url);