我需要一个简单的例子,在android中使用GraphQl
。
如何在android(教程)中使用GraphQl
。
答案 0 :(得分:5)
为了使用GraphQL(一般而言),您需要两件事:
有几种方法可以解决这个问题。当然,您可以使用您喜欢的任何服务器端语言来implement one yourself。 其他(更快)方法是利用现有工具并使用graphql-up或create-graphql-server等服务生成GraphQL API,甚至使用Graphcool等服务(免责声明:我为他们工作)。< / p>
虽然这个并不是绝对必要的,你也可以通过普通的HTTP(在POST请求的主体中发送你的查询和突变)简单地与GraphQL服务器交互,使用重复工作的现有工具当然是有益的。喜欢缓存或UI集成。目前最流行的GraphQL客户端之一是Apollo,他们也非常积极地处理version for Android。但是,这还没有正式发布。所以,你要么必须使用他们现有的开发版本,现在选择使用普通HTTP的前一种方法。
答案 1 :(得分:4)
以下是从Client查询GraphQl的示例。在这个例子中,我使用的是Retrofit 2:
connection.query("SELECT SUM(quantity) FROM report WHERE fabrika = ? ", fabrika, function(err, rows) {
if (err) console.log(err);
else {
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
var deger = JSON.stringify(row)
console.log("**********************************");
console.log("Possible Quantity: " + deger); //Possible Quantity: {"SUM(Quantity)":75}
console.log("**********************************");
}
}
});
答案 2 :(得分:0)
我个人使用翻新版,并且我拿了Link Credits 并改变了一些东西。
这是代码:
在文件“ GraphQLConverter.java”中:
public class GraphQLConverter extends Converter.Factory {
private static final MediaType MEDIA_TYPE = MediaType.parse("application/json; charset=UTF-8");
private GraphQueryProcessor graphProcessor;
private final Gson mGson;
private GraphQLConverter(Context context) {
graphProcessor = new GraphQueryProcessor(context);
mGson = new GsonBuilder()
.enableComplexMapKeySerialization()
.setLenient()
.create();
}
public static GraphQLConverter create(Context context) {
return new GraphQLConverter(context);
}
/** Override Converter.Factory Methods **/
@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
return null;
}
@Override
public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
if(type == QueryContainerBuilder.class){
return new GraphRequestConverter(methodAnnotations);
} else {
return null;
}
}
/** RequestConverter Class **/
private class GraphRequestConverter implements Converter<QueryContainerBuilder, RequestBody> {
private Annotation[] mAnnotations;
private GraphRequestConverter(Annotation[] annotations) {
mAnnotations = annotations;
}
@Override
public RequestBody convert(@NonNull QueryContainerBuilder containerBuilder) {
QueryContainerBuilder.QueryContainer queryContainer = containerBuilder
.setQuery(graphProcessor.getQuery(mAnnotations))
.build();
return RequestBody.create(MEDIA_TYPE, mGson.toJson(queryContainer).getBytes());
}
}
}
在“ GraphQuery.java”文件中:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface GraphQuery {
String value() default "";
}
在文件“ GraphQueryProcessor.java”中:
class GraphQueryProcessor {
private static final String TAG = GraphQueryProcessor.class.getSimpleName();
// GraphQl Constants
private static final String EXT_GRAPHQL = ".graphql";
private static final String ROOT_FOLDER_GRAPHQL = "graphql";
private final Map<String, String> mGraphQueries;
private Context mContext;
GraphQueryProcessor(Context context) {
mGraphQueries = new WeakHashMap<>();
mContext = context;
populateGraphQueries(ROOT_FOLDER_GRAPHQL);
}
/** Package-Private Methods **/
String getQuery(Annotation[] annotations) {
if(mGraphQueries == null || mGraphQueries.isEmpty()){
populateGraphQueries(ROOT_FOLDER_GRAPHQL);
}
GraphQuery graphQuery = null;
for (Annotation annotation : annotations) {
if (annotation instanceof GraphQuery) {
graphQuery = (GraphQuery) annotation;
break;
}
}
if (graphQuery != null) {
String fileName = String.format("%s%s", graphQuery.value(), EXT_GRAPHQL);
if (mGraphQueries != null && mGraphQueries.containsKey(fileName)) {
return mGraphQueries.get(fileName);
}
}
return null;
}
/** Private Methods **/
private void populateGraphQueries(@NonNull String path) {
try {
String[] paths = mContext.getAssets().list(path);
if (paths != null && paths.length > 0x0) {
for (String item : paths) {
String absolute = path + "/" + item;
if (!item.endsWith(EXT_GRAPHQL)) {
populateGraphQueries(absolute);
} else {
mGraphQueries.put(item, getFileContents(mContext.getAssets().open(absolute)));
}
}
}
} catch (IOException ioE) {
BaseEnvironment.onExceptionLevelLow(TAG, ioE);
}
}
private String getFileContents(InputStream inputStream) {
StringBuilder queryBuffer = new StringBuilder();
try {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
for (String line; (line = bufferedReader.readLine()) != null; )
queryBuffer.append(line);
inputStreamReader.close();
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
return queryBuffer.toString();
}
}
在“ QueryContainerBuilder.java”文件中:
public class QueryContainerBuilder {
// Mask Types
private static final byte MASK_REPLACE_QUERY_ARGUMENTS = 0b1; // Invece di inviare il json con le variabili va a inserirle nella query i valori sostituendo i tipi degli argomenti.
private static final byte MASK_REPLACE_EXPLICIT_QUOTES = MASK_REPLACE_QUERY_ARGUMENTS << 0b1; // Alle stringhe non vengono automaticamente messe le virgolette ma devono essere aggiunte nei valori passati per le variabili.
private static final byte MASK_REPLACE_WITH_PLACEHOLDERS = MASK_REPLACE_EXPLICIT_QUOTES << 0b1; // Va a sostituire i placeholders "<key_var_name>" presenti nella query con i valori delle variabili.
private QueryContainer mQueryContainer;
private byte mMask;
public QueryContainerBuilder() {
mQueryContainer = new QueryContainer();
}
/** Setter Methods **/
public QueryContainerBuilder setQuery(String query) {
mQueryContainer.setQuery(query);
return this;
}
public QueryContainerBuilder setReplaceQueryArguments(){
mMask = MASK_REPLACE_QUERY_ARGUMENTS;
return this;
}
public QueryContainerBuilder setReplaceExplicitQuotes(){
mMask = MASK_REPLACE_QUERY_ARGUMENTS | MASK_REPLACE_EXPLICIT_QUOTES;
return this;
}
public QueryContainerBuilder setReplaceWithPlaceholders(){
mMask = MASK_REPLACE_QUERY_ARGUMENTS | MASK_REPLACE_WITH_PLACEHOLDERS;
return this;
}
/** Public Methods **/
public QueryContainerBuilder putVariable(String key, Object value) {
mQueryContainer.putVariable(key, value);
return this;
}
public boolean containsVariable(String key) {
return mQueryContainer.containsVariable(key);
}
/** Builder Methods **/
public QueryContainer build() {
if((mMask & MASK_REPLACE_QUERY_ARGUMENTS) != 0x0){
if((mMask & MASK_REPLACE_WITH_PLACEHOLDERS) != 0x0){
mQueryContainer.replaceVariablesPlaceholdersInQuery();
} else {
mQueryContainer.replaceVariablesInQuery(mQueryContainer.mVariables, 0x0);
}
mQueryContainer.mVariables = null;
}
return mQueryContainer;
}
/** Public Static Classes **/
public class QueryContainer {
@SerializedName("variables")
private LinkedHashMap<String, Object> mVariables;
@SerializedName("query")
private String mQuery;
QueryContainer() {
mVariables = new LinkedHashMap<>();
}
/** Private Methods **/
private void setQuery(String query) {
mQuery = query;
}
private void putVariable(String key, Object value) {
mVariables.put(key, value);
}
private boolean containsVariable(String key) {
return mVariables != null && mVariables.containsKey(key);
}
private void replaceVariablesInQuery(LinkedHashMap<String, Object> map, int index){
if(!TextUtils.isEmpty(mQuery) && map.size() > 0x0){
List<String> keys = new ArrayList<>(map.keySet());
for(String key : keys){
Object value = map.get(key);
if(value instanceof LinkedHashMap){
replaceVariablesInQuery((LinkedHashMap<String, Object>) value, index);
} else {
int i = mQuery.indexOf(key + ":", index) + key.length() + 0x1;
int z;
if(keys.indexOf(key) < keys.size() - 0x1){
z = mQuery.indexOf(",", i);
} else {
z = mQuery.indexOf(")", i);
int x = mQuery.substring(i, z).indexOf('}');
if(x != -0x1){
if(mQuery.substring(i, i + 0x4).contains("{")){
x++;
}
z -= ((z - i) - x);
}
}
String replace;
if((mMask & MASK_REPLACE_EXPLICIT_QUOTES) != 0x0){
replace = String.valueOf(value);
} else {
replace = value instanceof String ?
"\"" + value.toString() + "\"" : String.valueOf(value);
}
String sub = mQuery.substring(i, z)
.replaceAll("[\\\\]?\\[", "\\\\\\[").replaceAll("[\\\\]?\\]", "\\\\\\]")
.replaceAll("[\\\\]?\\{", "\\\\\\{").replaceAll("[\\\\]?\\}", "\\\\\\}");
mQuery = mQuery.replaceFirst(sub.contains("{}") ? sub.replace("{}", "").trim() : sub.trim(), replace);
index = z + 0x1;
}
}
}
}
private void replaceVariablesPlaceholdersInQuery(){
if(!TextUtils.isEmpty(mQuery) && mVariables.size() > 0x0){
for(String key : mVariables.keySet()){
mQuery = mQuery.replaceFirst("\\<" + key + "\\>", mVariables.get(key) != null ? mVariables.get(key).toString() : "null");
}
mVariables = null;
}
}
}
}
将查询放入带有“ .graphql”扩展名的查询文件的“ assets”文件夹中的“ graphql”目录中。您可以通过更改“ GraphQueryProcessor”中的“ EXT_GRAPHQL”或“ ROOT_FOLDER_GRAPHQL”常量来更改扩展名或文件夹。您可以将以下格式用于查询:
query {
myQuery(param1: <myParam1>) {
....
}
}
如果使用这种格式,则需要在QueryContainerBuilder中使用“ MASK_REPLACE_WITH_PLACEHOLDERS” 。另外,您需要将不带“ <...>”的占位符的名称作为HashMap键传递,因此在这种情况下为“ myParam1”。
其他格式只是常见的GraphQL查询,例如:
query ($p1: String!) {
muQuery(p1: $id) {
...
}
}
使用这种格式,您可以使用常规QueryContainerBuilder行为(未应用掩码,因此它将通过并生成“变量” json对象。)或“ MASK_REPLACE_QUERY_ARGUMENTS” 这将删除“ $ id”并放置值。
初始化改造时,添加“ GraphQLConverter” 。请注意“ ConvertFactories”的顺序!!您可以放置更多的ConvertFactory,但是它们会消耗输入,因此,如果在这种情况下,将“ Gson”放在“ GraphQL”之前,则“ GsonConverted”将使用输入数据:
new Retrofit.Builder()
.baseUrl(mBaseUrl)
.addConverterFactory(GraphQLConverter.create(context))
.addConverterFactory(GsonConverterFactory.create(gson))
.client(getBaseHttpClient(interceptor))
.build();
在您的翻新API中:
@POST(AppConstants.SERVICE_GQL)
@GraphQuery(AppConstants.MY_GRAPHQL_QUERY_FILENAME)
fun callMyGraphQlQuery(@Body query: QueryContainerBuilder): Call<MyGraphQlResponse>
通话示例:
val query = QueryContainerBuilder()
.putVariable("myParam1", myValue)
.setReplaceWithPlaceholders()
createService(API::class.java).callMyGraphQlQuery(query)
val query = QueryContainerBuilder()
.putVariable("p1", myValue)
.setReplaceQueryArguments()
createService(API::class.java).callMyGraphQlQuery(query)
val query = QueryContainerBuilder()
.putVariable("p1", myValue)
createService(API::class.java).callMyGraphQlQuery(query)
如果“ MASK_REPLACE_QUERY_ARGUMENTS”工作正常,我会同意,我只使用了2/3次,然后更改了后端并写得更好。
我做了那些事例(掩码)来处理查询,因为我有这3种事例与我正在调用的后端一起进行。 您可以仅通过在“ QueryContainerBuilder”中添加另一个掩码和代码来添加其他查询处理行为。
如果有人使用此代码并对其进行了更改以使其更好,请把更改写给我,以便我也更改我库中的代码。
谢谢你, 编码不错,每天:D
再见!
答案 3 :(得分:0)
在您的清单中添加
<uses-permission android:name="android.permission.INTERNET"/>
你的依赖
// Kotlin Coroutines
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.4'
//OkHttp
implementation ("com.squareup.okhttp3:okhttp:3.12.12"){
force = true //API 19 support
}
implementation 'com.squareup.okhttp3:logging-interceptor:3.12.12'
//retrofit
implementation "com.squareup.retrofit2:retrofit:2.7.1"
implementation "com.squareup.retrofit2:converter-scalars:$2.7.1"
还兼容 Java 8
android {
...
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = "1.8"
}
}
随着服务
import retrofit2.Response
import retrofit2.http.Body
import retrofit2.http.Headers
import retrofit2.http.POST
interface GraphQLService {
@Headers("Content-Type: application/json")
@POST("/")
suspend fun postDynamicQuery(@Body body: String): Response<String>
}
你可以创建一个对象
import retrofit2.Retrofit
import retrofit2.converter.scalars.ScalarsConverterFactory
object GraphQLInstance {
private const val BASE_URL: String = "http://192.155.1.55:2000/"
val graphQLService: GraphQLService by lazy {
Retrofit
.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(ScalarsConverterFactory.create())
.build().create(GraphQLService::class.java)
}
}
在活动中你可以创建这个方法
private fun post(userId: String){
val retrofit = GraphQLInstance.graphQLService
val paramObject = JSONObject()
paramObject.put("query", "query {users(userid:$userId){username}}")
GlobalScope.launch {
try {
val response = retrofit.postDynamicQuery(paramObject.toString())
Log.e("response", response.body().toString())
}catch (e: java.lang.Exception){
e.printStackTrace()
}
}
}
您可以检查 the example in GitHub 和 my post
注意:如果你需要一个mutation应该是改变这一行
paramObject.put("query", "query {users(userid:$userId){username}}")
到
paramObject.put("query", "mutation {users(userid:$userId){username}}")