OkHttp不能正常工作

时间:2017-03-10 06:23:36

标签: java android okhttp

我是Android Dev的新手,我创建了一个Google表单并想在我的应用上实现该表单,我听说Square开源的开源 okhttp ,你很可能知道

所以,我用标签创建了一个布局,给了他们相同的ID和一切...... 我创建了一个名为 Form 的java类,并插入了所有代码,没有任何错误。

(值得一提的是我正在使用导航抽屉活动,但不知道这是否会影响)

因此,在实施和纠正所有内容之后,我会运行应用程序,但它并没有做任何事情。它不进行验证,也不发送响应。

如果有人能帮我解决这个问题,我真的很感激

我会在这里留下代码

再一次,谢谢。

package com.example.eduardobastos.testapp;


import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;


public class Form extends AppCompatActivity {

public static final MediaType FORM_DATA_TYPE
        = MediaType.parse("application/x-www-form-urlencoded; charset=utf-8");
//URL derived from form URL
public static final String URL="https://docs.google.com/forms/d/e/1FAIpQLSeZp9wjprZJ3OR2SkIHHsZE9yDBAVnC7mO8hPKSzwGuYhqmdw/formResponse";
//input element ids found from the live form page
public static final String EMAIL_KEY="entry_943499687";
public static final String SUBJECT_KEY="entry_2058392291";
public static final String MESSAGE_KEY="entry_1420026128";

private Context context;
private EditText emailEditText;
private EditText subjectEditText;
private EditText messageEditText;

@Override
protected void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.form_layout);

    //save the activity in a context variable to be used afterwards
    context =this;

    //Get references to UI elements in the layout
    Button sendButton = (Button)findViewById(R.id.sendButton);
    emailEditText = (EditText)findViewById(R.id.emailEditText);
    subjectEditText = (EditText)findViewById(R.id.subjectEditText);
    messageEditText = (EditText)findViewById(R.id.messageEditText);

    sendButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            //Make sure all the fields are filled with values
            if(TextUtils.isEmpty(emailEditText.getText().toString()) ||
                    TextUtils.isEmpty(subjectEditText.getText().toString()) ||
                    TextUtils.isEmpty(messageEditText.getText().toString()))
            {
                Toast.makeText(context,"All fields are mandatory.",Toast.LENGTH_LONG).show();
                return;
            }
            //Check if a valid email is entered
            if(!android.util.Patterns.EMAIL_ADDRESS.matcher(emailEditText.getText().toString()).matches())
            {
                Toast.makeText(context,"Please enter a valid email.",Toast.LENGTH_LONG).show();
                return;
            }

            //Create an object for PostDataTask AsyncTask
            PostDataTask postDataTask = new PostDataTask();

            //execute asynctask
            postDataTask.execute(URL,emailEditText.getText().toString(),
                    subjectEditText.getText().toString(),
                    messageEditText.getText().toString());
        }
    });
}



//AsyncTask to send data as a http POST request
private class PostDataTask extends AsyncTask<String, Void, Boolean> {

    @Override
    protected Boolean doInBackground(String... contactData) {
        Boolean result = true;
        String url = contactData[0];
        String email = contactData[1];
        String subject = contactData[2];
        String message = contactData[3];
        String postBody="";

        try {
            //all values must be URL encoded to make sure that special characters like & | ",etc.
            //do not cause problems
            postBody = EMAIL_KEY+"=" + URLEncoder.encode(email,"UTF-8") +
                    "&" + SUBJECT_KEY + "=" + URLEncoder.encode(subject,"UTF-8") +
                    "&" + MESSAGE_KEY + "=" + URLEncoder.encode(message,"UTF-8");
        } catch (UnsupportedEncodingException ex) {
            result=false;
        }



        try{
            //Create OkHttpClient for sending request
            OkHttpClient client = new OkHttpClient();
            //Create the request body with the help of Media Type
            RequestBody body = RequestBody.create(FORM_DATA_TYPE, postBody);
            Request request = new Request.Builder()
                    .url(url)
                    .post(body)
                    .build();
            //Send the request
            Response response = client.newCall(request).execute();
        }catch (IOException exception){
            result=false;
        }
        return result;
    }

    @Override
    protected void onPostExecute(Boolean result){
        //Print Success or failure message accordingly
        Toast.makeText(context,result?"Message successfully sent!":"There was some error in sending message. Please try again after some time.",Toast.LENGTH_LONG).show();
    }

}

}

1 个答案:

答案 0 :(得分:0)

刚试过这个,就像魅力......

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.widget.TextViewCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import butterknife.BindView;
import butterknife.ButterKnife;
import mx.com.iisi.staffing.R;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MessageActivity extends AppCompatActivity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_message);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    @Override
    protected void onResume() {
        super.onResume();
        new PostDataTask(this).execute("","testing@testing.com","Testing","Testing message");
    }

    private class PostDataTask extends AsyncTask<String, Void, Boolean> {

        public final MediaType FORM_DATA_TYPE
                = MediaType.parse("application/x-www-form-urlencoded; charset=utf-8");
        //URL derived from form URL
        public static final String URL="https://docs.google.com/forms/d/e/1FAIpQLSeZp9wjprZJ3OR2SkIHHsZE9yDBAVnC7mO8hPKSzwGuYhqmdw/formResponse";
        //input element ids found from the live form page
        public static final String EMAIL_KEY="entry_943499687";
        public static final String SUBJECT_KEY="entry_2058392291";
        public static final String MESSAGE_KEY="entry_1420026128";
        private Context context;

        public PostDataTask(Context context)
        {
            this.context = context;
        }

        @Override
        protected Boolean doInBackground(String... contactData) {
            Boolean result = true;
            String url = contactData[0];
            String email = contactData[1];
            String subject = contactData[2];
            String message = contactData[3];
            String postBody="";

            try {
                //all values must be URL encoded to make sure that special characters like & | ",etc.
                //do not cause problems
                postBody = EMAIL_KEY+"=" + URLEncoder.encode(email,"UTF-8") +
                        "&" + SUBJECT_KEY + "=" + URLEncoder.encode(subject,"UTF-8") +
                        "&" + MESSAGE_KEY + "=" + URLEncoder.encode(message,"UTF-8");
            } catch (UnsupportedEncodingException ex) {
                result=false;
            }



            try{
                //Create OkHttpClient for sending request
                OkHttpClient client = new OkHttpClient();
                //Create the request body with the help of Media Type
                RequestBody body = RequestBody.create(FORM_DATA_TYPE, postBody);
                Request request = new Request.Builder()
                        .url(URL)
                        .post(body)
                        .build();
                //Send the request
                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();
        }

    }
}