gpt4 book ai didi

android - ruby on rails 中用于 Android 操作系统的 API

转载 作者:行者123 更新时间:2023-11-29 22:14:27 25 4
gpt4 key购买 nike

我需要提供一个 RESTful api,以便在 ruby​​ on rails 中为 android 应用程序开发具有 CRUD 功能。我之前没有使用过与 RoR 集成的手机操作系统(android/iphone)。所以,请帮助我开始。

提前致谢。

最佳答案

您可以将数据作为 Json 数据包发送到设备,并在设备中解析 json 数据包并访问数据。您对 webservice 的调用应该是一个 http 调用,例如这是给客户端的。

http:\server\metnod\get_somedata?name=something

并且服务器应该查询数据库以获取此参数并将响应作为 Json 发送给您。解析 json 并获取您的详细信息。

String url = "http:\\example.com\mycontroller\get_employee?id=2"

HttpPost httpPostRequest = new HttpPost(url);
StringEntity se;
se = new StringEntity(jsonObjSend.toString());


httpPostRequest.setEntity(se);
httpPostRequest.setHeader("Authorization", usercredential);
httpPostRequest.setHeader("Accept", "application/json");
httpPostRequest.setHeader("Content-type", "application/json");

long t = System.currentTimeMillis();
response = (HttpResponse) httpclient.execute(httpPostRequest);
Log.i(TAG, "HTTPResponse received in [" + (System.currentTimeMillis()-t) + "ms]");

HttpEntity entity = response.getEntity();

if (entity != null) {

InputStream instream = entity.getContent();
Header contentEncoding = response.getFirstHeader("Content-Encoding");
if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
instream = new GZIPInputStream(instream);
}

// convert content stream to a String
String resultString= convertStreamToString(instream);
Log.v(null, "resultString "+resultString);
instream.close();


// Transform the String into a JSONObject
if(resultString!=null){
jsonObjRecv = new JSONObject(resultString);

}

// Raw DEBUG output of our received JSON object:
Log.i(TAG,"<jsonobject>\n"+jsonObjRecv.toString()+"\n</jsonobject>");

return jsonObjRecv;

在服务器端,您应该在名为 mycontroller 的 Controller 中有一个 get_employee 方法。在该方法中,您可以将请求作为普通的 http 请求进行处理,并将响应作为 json 发送,例如

employee = Employee.find_by_id(params[:id])
@js_response = ActiveSupport::JSON.encode(employee)
respond_to do |format|
format.json { render :json => @js_response}
format.html
end

对于 CRUD,您需要使用适当的参数创建不同的方法,例如 delete_employee、update_employee 等。引用 json.org 在 android 中创建/解析 json

关于android - ruby on rails 中用于 Android 操作系统的 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8800703/

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