我正在尝试使用 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());
}
}