Android中的REDCap API导入记录

Posted

技术标签:

【中文标题】Android中的REDCap API导入记录【英文标题】:REDCap API import records in Android 【发布时间】:2016-03-03 18:26:00 【问题描述】:

我正在尝试使用 REDCap API 通过 android 应用程序导入记录。如何使活动中的按钮在单击时运行以下代码以便将数据上传到 REDCap?如果有另一种编码方式,那将同样有帮助。我基本上想使用他们已经给我的 API 令牌和 URL 将 JSON 对象中的数据发送到 REDCap。

package com.example.maciej.fuglmeyer;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;


public class MyClass

    private final HttpPost post;
    private final HttpClient client;
    private int respCode;
    private BufferedReader reader;
    private final StringBuffer result;
    private String line;

    @SuppressWarnings("unchecked")
    public MyClass(final Config c)
    
        JSONObject record = new JSONObject();
        record.put("record_id", "3");
        record.put("first_name", "First");
        record.put("last_name", "Last");
        record.put("address", "123 Cherry Lane\nNashville, TN 37015");
        record.put("telephone", "(615) 255-4000");
        record.put("email", "first.last@gmail.com");
        record.put("dob", "1972-08-10");
        record.put("age", "43");
        record.put("ethnicity", "1");
        record.put("race", "4");
        record.put("sex", "1");
        record.put("height", "180");
        record.put("weight", "105");
        record.put("bmi", "31.4");
        record.put("comments", "comments go here");
        record.put("demographics_complete", "2");

        JSONArray data = new JSONArray();
        data.add(record);

        List<NameValuePair> params = new ArrayList<>();
        params.add(new BasicNameValuePair("token", "123423412342134"));
        params.add(new BasicNameValuePair("content", "record"));
        params.add(new BasicNameValuePair("format", "json"));
        params.add(new BasicNameValuePair("type", "flat"));
        params.add(new BasicNameValuePair("data", data.toJSONString()));

        post = new HttpPost("URLGOESHERE.com");
        post.setHeader("Content-Type", "application/x-www-form-urlencoded");

        try
        
            post.setEntity(new UrlEncodedFormEntity(params));
        
        catch (final Exception e)
        
            e.printStackTrace();
        

        result = new StringBuffer();
        client = HttpClientBuilder.create().build();
        respCode = -1;
        reader = null;
        line = null;
    

    public void doPost()
    
        HttpResponse resp = null;

        try
        
            resp = client.execute(post);
        
        catch (final Exception e)
        
            e.printStackTrace();
        

        if(resp != null)
        
            respCode = resp.getStatusLine().getStatusCode();

            try
            
                reader = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
            
            catch (final Exception e)
            
                e.printStackTrace();
            
        

        if(reader != null)
        
            try
            
                while((line = reader.readLine()) != null)
                
                    result.append(line);
                
            
            catch (final Exception e)
            
                e.printStackTrace();
            
        

        System.out.println("respCode: " + respCode);
        System.out.println("result: " + result.toString());
    

【问题讨论】:

您在私人 REDCap 论坛上问过这个问题吗?如果不成功,请向您校园的 REDCap 管理员索取“redcap-api-examples.zip”文件,该文件可从yourredcapserver.edu/redcap/api/help/?content=examples 下载。有几个java示例;一个类似于您上面的代码,但有一些范围差异。 【参考方案1】:

1) 创建一个简单的Layout,其中包含一个Button 和一个EditText,用于上传数据:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/parent_log"
    android:layout_
    android:layout_
    android:orientation="vertical"
    android:paddingBottom="16dp"
    android:paddingEnd="16dp"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:paddingStart="16dp"
    android:paddingTop="16dp">

    <EditText
        android:id="@+id/input_name"
        android:layout_
        android:layout_
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="8dp"
        android:ems="10"
        android:hint="Exemplo: João da Silva"
        android:inputType="textPersonName" />

     <Button
        android:layout_
        android:layout_
        android:text="CADASTRAR"
        android:id="@+id/uploadData"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="16dp"
        android:onClick="onClick" />

 </LinearLayout>

2) 在 Activity 的 onClick 方法中,获取数据并调用 Class ConfigImportData (REDCap API 上的 Java 示例中的内容)

public void onClick(View v) 
    String name = findViewById(R.id.input_name).getText().toString();

    Config config = new Config();

    //I have changed the constructor to send the only string that will be
    //uploaded, but you can send a context, array of strings, whatever...
    ImportRecords importRecords = new ImportRecords(config, name);
    importRecords.doPost();

3) 在 ImportRecords 上,您发布的类,更改构造函数(如果需要),这是您可以执行的代码示例

public class ImportRecords 
private final List<NameValuePair> params;
private final HttpPost post;
private HttpResponse resp;
private final HttpClient client;
private int respCode;
private BufferedReader reader;
private final StringBuffer result;
private String line;
private final JSONObject record;
private final JSONArray data;
private String recordID;
//private final SecureRandom random;

@SuppressWarnings("unchecked")
public ImportRecords(final Config c, String name) 
    //Create an id. Id is the record identifier
    //For example if you want get the record in the future, you'll need that
    Random r = new Random();
    int id = r.nextInt();

    record = new JSONObject();
    record.put("record_id", id);
    record.put("first_name", name);

    data = new JSONArray();
    data.add(record);

    params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("token", c.API_TOKEN));
    params.add(new BasicNameValuePair("content", "record"));
    params.add(new BasicNameValuePair("format", "json"));
    params.add(new BasicNameValuePair("type", "flat"));
    params.add(new BasicNameValuePair("data", data.toJSONString()));
    params.add(new BasicNameValuePair("forms", "pergunta"));

    //c.API_URL is the url found on your REDCap project - API
    post = new HttpPost(c.API_URL);
    post.setHeader("Content-Type", "application/x-www-form-urlencoded");

    try 
        post.setEntity(new UrlEncodedFormEntity(params));
     catch (final Exception e) 
        e.printStackTrace();
    

    result = new StringBuffer();
    client = HttpClientBuilder.create().build();
    respCode = -1;
    reader = null;
    line = null;

4) 在 Android 上,Post 方法需要在后台运行。我为此创建了一个 AsyncTask

public void doPost() 
    new Task().execute();


public class Task extends AsyncTask<Void, Void, Boolean> 

    @Override
    protected Boolean doInBackground(Void... params) 
        resp = null;

        try 
            resp = client.execute(post);
         catch (final Exception e) 
            e.printStackTrace();
            return false;
        

        if (resp != null) 
            respCode = resp.getStatusLine().getStatusCode();


            try 
                reader = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
             catch (final Exception e) 
                e.printStackTrace();
                return false;
            
        

        if (reader != null) 
            try 
                while ((line = reader.readLine()) != null) 
                    result.append(line);
                
             catch (final Exception e) 
                e.printStackTrace();
                return false;
            
        

        System.out.println("respCode: " + respCode);
        System.out.println("result: " + result.toString());
        if (respCode!=200)
            return false;
        return true;
    

    @Override
    protected void onPostExecute(Boolean aBoolean) 
        super.onPostExecute(aBoolean);
        if (aBoolean)
            Log.e("RESULT","The record was sent");
        else
            Log.e("RESULT","The record was not sent");
    

【讨论】:

以上是关于Android中的REDCap API导入记录的主要内容,如果未能解决你的问题,请参考以下文章

什么是 RedCap?一文详解!

视频到底什么是RedCap?

视频到底什么是RedCap?

视频到底什么是RedCap?

R17 redcap

Kitkat 中的 Android 相机 API 2