如何从服务器获取响应 [英] How to getback response from server

查看:125
本文介绍了如何从服务器获取响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个Android应用程序,需要进一步进行电子邮件验证才能继续操作.我有一个简单的edittext字段,用户可以在其中输入电子邮件并单击继续按钮.单击继续按钮后,我已将该电子邮件发送到服务器.后端电子邮件用户发送的邮件将首先得到检查.如果已验证电子邮件的数据库中有该电子邮件,则允许该用户继续进行下一个活动,否则其他用户应该得到一些信息,表明他们的电子邮件未经过验证.为此,我这样做了在我的Android应用程序Java类中

I am doing an android app which requires email verification before moving further.I have a simple edittext field where user enters their email and clicks to proceed button.On clicking to proceed button I have sent that email to server.I wish in backend the email user sends get checked first.If the email is available in the database of verified emails then the user is allowed to Proceed to next activity,else user should get some messeges that their email isn't verified.For this I did this in my android app java class

  package fragment;


import android.app.Activity;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.user.timothysurvey.R;
import com.example.user.timothysurvey.activity.Introduction;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

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

import pojo.Email;
import pojo.JSONParser;

/**
 * A simple {@link Fragment} subclass.
 */
public class Ongoing extends Fragment {


    Button proceed;
    EditText email;
    TextView surveyTitle;
    String success;

    private static final String url="http://192.168.0.123/survey/public/api/verifyemail";

    public Ongoing() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v=inflater.inflate(R.layout.fragment_ongoing, container, false);
        surveyTitle= (TextView) v.findViewById(R.id.surveyTitle);
        email = (EditText) v.findViewById(R.id.email);
        proceed= (Button) v.findViewById(R.id.proceed);
        proceed.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isConnected()) {

                    String emailAddress = email.getText().toString().trim();
                    String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+";

                    if (emailAddress.matches("")) {

                        Toast.makeText(getContext(), "Please fill up all the fields", Toast.LENGTH_LONG).show();

                    } else {
                        if (emailAddress.matches(emailPattern)) {
                            new HttpAsyncTask().execute("http://192.168.0.123/survey/public/api/verifyemail");
                        } else
                            Toast.makeText(getContext(), "Invalid Email Address", Toast.LENGTH_LONG).show();
                    }
                }
            else {

                Toast.makeText(getContext(), "Please check your internet connection", Toast.LENGTH_LONG).show();
            }
            }
        });
        return v;
    }

    private class HttpAsyncTask extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... urls) {

            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("email", email.getText().toString()));
            JSONParser jParser = new JSONParser();
            JSONObject json = jParser.makeHttpRequest(url, "POST", params);
            try {
                success = json.getString("success");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }
        @Override
        protected void onPostExecute(String result) {
            if(success.equals("Email verified. Please proceed with survey"))
                Toast.makeText(getContext(), "Wait For a moment", Toast.LENGTH_LONG).show();
        }
    }

    public boolean isConnected(){
        ConnectivityManager connMgr = (ConnectivityManager) getActivity().getSystemService(Activity.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected())
            return true;
        else
            return false;
    }

}

这是我后端的php代码

And this is my php code for the backend

<?php

use Illuminate\Http\Request;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
 */

// url
// :: localhost/api/verifyemail/anish@gmail.com

// messages
// 1. No record in database
// 2. Admin has not verified your email
// 3. Email verified. Please proceed with survey

Route::get('verifyemail/{email}', function ($email) {
    // first check whether user exist in database
    $user = \App\SurveyUser::where('email', $email)->first();

    // if user does not exist send error message
    if (empty($user)) {
        $user['error'] = 'No record in database';
    } else {
        if ($user->verified_by_admin) {
            $user['success'] = 'Email verified. Please proceed with survey';
        } else {
            $user['error'] = 'Admin has not verified your email';
        }
    }

    return $user;
    // if exist check whether he is allowed to take survey or not
});

Route::post('verifyemail', function (Request $request) {
    // check email
    $email = $request->email;

    $user = \App\SurveyUser::where('email', $email)->first();
    if (empty($user)) {
        $user['error'] = 'No record in database';
    } else {
        if ($user->verified_by_admin) {
            $user['success'] = 'Email verified. Please proceed with survey';
        } else {
            $user['error'] = 'Admin has not verified your email';
        }
    }
    return $user;
});

Route::get('/user', function (Request $request) {
    return $request->user();
})->middleware('auth:api');

我没有从上面的代码中得到任何结果.有人建议我以正确的方式实现目标.谢谢您

I am not getting any result from above code.Somebody Please suggest me the right way I could achieve my target.Thank you in advance

推荐答案

定义一个全局字符串变量:

Define a global string variable :

Button proceed;
EditText email;
TextView surveyTitle;
String success;

像这样更新HttpAsyncTask:

Update HttpAsyncTask like this :

private class HttpAsyncTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {

        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("email", email.getText().toString()));
        JSONParser jParser = new JSONParser();
        JSONObject json = jParser.makeHttpRequest(url, "POST", params);
        try {
            success = json.getString("success");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }
    @Override
    protected void onPostExecute(String result) {
        if(success.equals("Email verified. Please proceed with survey"))
            Toast.makeText(getContext(), "Wait For a moment", Toast.LENGTH_LONG).show();
    }
}

最后创建像这样的JSONParser类:

And finally create JSONParser class like this :

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

public JSONParser() {

}

public JSONObject getJSONFromUrl(final String url) {

    try {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;

        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }

        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    return jObj;

}

public JSONObject makeHttpRequest(String url, String method,
        List<NameValuePair> params) {

    try {

        if (method == "POST") {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(params));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        } else if (method == "GET") {
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(params, "utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    return jObj;
} }

这篇关于如何从服务器获取响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆