我想制作一个Android应用程序,谷歌电子表格将成为我的服务器。我能够通过谷歌表格将数据发布到服务器(谷歌电子表格),但无法从该电子表格中获取数据。 我的代码是
公共类ContactActivity扩展了ActionBarActivity {
public static final MediaType FORM_DATA_TYPE
= MediaType.parse("application/x-www-form-urlencoded; charset=utf-8");
public static final String URL="https://docs.google.com/forms/d/e/" +
"XXXXXXXXX/formResponse";
public static final String NAME="entry.XXXXXXXX";
public static final String PHONE="entry.XXXXXXXX7";
public static final String EMAIL="entry.XXXXXXXX";
private Context context;
private EditText name;
private EditText ph;
private EditText email;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact);
context =this;
Button sendButton = (Button)findViewById(R.id.submit);
name = (EditText)findViewById(R.id.name);
ph = (EditText)findViewById(R.id.phone);
email = (EditText)findViewById(R.id.email);
sendButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(TextUtils.isEmpty(name.getText().toString()) ||
TextUtils.isEmpty(ph.getText().toString()) ||
TextUtils.isEmpty(email.getText().toString()))
{
Toast.makeText(context,"All fields are mandatory.",Toast.LENGTH_LONG).show();
return;
}
if(!android.util.Patterns.EMAIL_ADDRESS.matcher(email.getText().toString()).matches())
{
Toast.makeText(context,"Please enter a valid email.",Toast.LENGTH_LONG).show();
return;
}
PostDataTask postDataTask = new PostDataTask();
postDataTask.execute(URL,name.getText().toString(),ph.getText().toString(),email.getText().toString());
}
});
}
private class PostDataTask extends AsyncTask<String, Void, Boolean> {
@Override
protected Boolean doInBackground(String... contactData) {
Boolean result = true;
String url = contactData[0];
String n = contactData[1];
String p = contactData[2];
String e = contactData[3];
String postBody="";
try {
postBody = NAME+"=" + URLEncoder.encode(n,"UTF-8") +
"&" + PHONE + "=" + URLEncoder.encode(p,"UTF-8") +
"&" + EMAIL + "=" + URLEncoder.encode(e,"UTF-8");
} catch (UnsupportedEncodingException ex) {
result=false;
}
try{
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(FORM_DATA_TYPE, postBody);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
}catch (IOException exception){
result=false;
}
return result;
}
@Override
protected void onPostExecute(Boolean result){
Toast.makeText(context,result?"Message successfully sent!":"There was some error in sending message. Please try again after some time.",Toast.LENGTH_LONG).show();
}
}
}