【问题标题】:Pass parameter using HTTP GET in Android在 Android 中使用 HTTP GET 传递参数
【发布时间】:2014-05-01 12:12:24
【问题描述】:

在我的应用程序的一个视图中,我有 ListView,它使用 Listadapter、JSON、PHP 等显示 MySQL 数据库中的数据。所有这些都有效,但我试图弄清楚(没有成功)是如何我可以向 PHP 发送一个参数,这样我就可以检索不是所有的配置文件(在我的应用程序的情况下),而是我想要的那些,具体取决于用户 ID。

这是构成 HTTP 的 AsynTask 代码

private class GetProfiles extends AsyncTask<String, Void, String>{

    private ProgressDialog pDialog;
    private String message;
    private final GetProfilesListener listener;

    /**
     * Method to set listener value.
     */
    public GetProfiles(GetProfilesListener listener){
        this.listener = listener;
    }

    protected void onPreExecute(){
        super.onPreExecute();

        pDialog = new ProgressDialog(UserProfiles.this);
        pDialog.setTitle("Contacting Server");
        pDialog.setMessage("Loading profile(s)...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    protected String doInBackground(String... params) {
        if (params == null ) 
            return null;

        String url = params[0];

         try {
                // create http connection
                HttpClient client = new DefaultHttpClient();
                HttpGet httpget = new HttpGet(url);

                // connect
                HttpResponse response = client.execute(httpget);

                // get response
                HttpEntity entity = response.getEntity();

                if(entity == null) {
                    message = "No response from server";
                    return null;        
                }

                // get response content and convert it to json string
                InputStream is = entity.getContent();
                return streamToString(is);
            }
            catch(IOException e){
                message = "No Network Connection";
            }

         return null;
    }


      @Override
        protected void onPostExecute(String sJson) {
            if(sJson == null) {
                if(listener != null) listener.onFetchFailure(message);
                return;
            }        

            try {
                // convert json string to json array
                JSONArray aJson = new JSONArray(sJson);
                // create profiles list
                List<Profiles> profiles = new ArrayList<Profiles>();

                for(int i=0; i<aJson.length(); i++) {
                    JSONObject json = aJson.getJSONObject(i);
                    Profiles pro = new Profiles();
                    pro.setProfileName(json.getString("profilename"));
                    pro.setPetType(json.getString("pettype"));
                    pro.setUsername(json.getString("username"));
                    pro.setProfileid(Integer.parseInt(json.getString("profileid")));

                    pDialog.dismiss();

                    // add profile to profiles list
                    profiles.add(pro);

                }

                //notify the activity that fetch data has been complete
                if(listener != null) listener.onFetchComplete(profiles);
            } catch (JSONException e) {
                message = "Invalid response";
                if(listener != null) listener.onFetchFailure(message);
                return;
            }        
        }

我知道我的一个参数是 url,上面写着String url = param[0] 我只是不知道如何在代码中添加另一个参数,该参数将在服务器端用于根据 ID 或名称等检索信息. 我试图建立这样的参数:

List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair(TAG_AID, adid));

但它不允许我。

【问题讨论】:

  • 可能对你有帮助:HttpGet httpget = new HttpGet(url +"?" + key + " = " + value);
  • 嗨,值是我的变量,但关键是什么?
  • @LucianoSantis 这由您决定。您只需要知道您从 android 发送的内容,就可以知道在您的服务器中查找什么
  • 在服务器端,有一个变量存放着value
  • 我通常在服务器端做的是这样的: if (isset($_GET["adid"])) { $adid = $_GET['adid'];并且那个 addid 值来自 android 端,我将它发送到 php,如下所示: List params = new ArrayList(); params.add(new BasicNameValuePair("adid", adid));但这种方式是不同的,所以我可以在 PHP 中以与我在这里相同的方式获得该值还是我必须知道其他内容?

标签: android android-asynctask http-get


【解决方案1】:

您可以重载异步任务构造函数并将您的键值参数传递给成员变量,然后在您想要发送 http get 请求时使用它。请在下面找到代码

private class GetProfiles extends AsyncTask<String, Void, String>{

private ProgressDialog pDialog;
private String message;
private final GetProfilesListener listener;
protected HashMap< String, String > queryStringParams;


/**
 * Method to set listener value.
 */
public GetProfiles(GetProfilesListener listener,HashMap< String, String > queryStringParams ){
    this.listener = listener;
    this.queryStringParams =queryStringParams;
}

protected void onPreExecute(){
    super.onPreExecute();

    pDialog = new ProgressDialog(UserProfiles.this);
    pDialog.setTitle("Contacting Server");
    pDialog.setMessage("Loading profile(s)...");
    pDialog.setIndeterminate(false);
    pDialog.setCancelable(true);
    pDialog.show();
}

@Override
protected String doInBackground(String... params) {
    if (params == null ) 
        return null;

    String url = params[0];
    //here u can use the queryString hash map parameters that u passed
    url+="uid="+queryStringParams.get("UID");//for example

     try {
            // create http connection
            HttpClient client = new DefaultHttpClient();
            HttpGet httpget = new HttpGet(url);

            // connect
            HttpResponse response = client.execute(httpget);

            // get response
            HttpEntity entity = response.getEntity();

            if(entity == null) {
                message = "No response from server";
                return null;        
            }

            // get response content and convert it to json string
            InputStream is = entity.getContent();
            return streamToString(is);
        }
        catch(IOException e){
            message = "No Network Connection";
        }

     return null;
}

所以现在您可以在调用异步任务时发送参数,如下所示

    queryStringParams= new HashMap<String, String>();
    queryStringParams.put("UID", "12")
    new getListItems(listener, queryStringParams).execute(); 

希望这会有所帮助。

【讨论】:

  • 您好,感谢您的帮助,我会尝试这个解决方案,看看它是否对我有帮助。
【解决方案2】:

你也可以这样做:

protected String addLocationToUrl(String url){
if(!url.endsWith("?"))
    url += "?";

List<NameValuePair> params = new LinkedList<NameValuePair>();

if (lat != 0.0 && lon != 0.0){
    params.add(new BasicNameValuePair("lat", String.valueOf(lat)));
    params.add(new BasicNameValuePair("lon", String.valueOf(lon)));
}

if (address != null && address.getPostalCode() != null)
    params.add(new BasicNameValuePair("postalCode", address.getPostalCode()));
if (address != null && address.getCountryCode() != null)
    params.add(new BasicNameValuePair("country",address.getCountryCode()));

params.add(new BasicNameValuePair("user", agent.uniqueId));

String paramString = URLEncodedUtils.format(params, "utf-8");

url += paramString;
return url;
}

【讨论】:

    【解决方案3】:
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.util.ArrayList;
    
    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.DefaultHttpClient;
    import org.apache.http.message.BasicNameValuePair;
    import org.apache.http.params.BasicHttpParams;
    import org.apache.http.params.HttpConnectionParams;
    import org.apache.http.params.HttpParams;
    import org.json.JSONException;
    import org.json.JSONObject;
    
    import android.app.Activity;
    import android.app.AlertDialog;
    import android.app.ProgressDialog;
    import android.content.Context;
    import android.content.DialogInterface;
    import android.content.Intent;
    import android.content.SharedPreferences;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.widget.Toast;
    
    public class MainActivity extends Activity
    {
        public EditText uname,pwd;
        Button btnlog1;
        TextView invalid;
        public Button btncancel1;
        public String db_select;
         String mUname;
         String mPwd;
        String temp;
        Intent intObj;
        Intent intent = null;
    
    Boolean isInternetPresent = false;
        ConnectionDetector cd;
    
    
        private String SERVICE_URL = "http://10.54.3.208:8080";
    
        private final String TAG = "MainActivity";
        public static final String PREFS_NAME = "MyPrefsFile";
        @Override
        protected void onCreate(Bundle savedInstanceState) 
        {
            super.onCreate(savedInstanceState);
            MainActivity.this.setContentView(R.layout.activity_main);
            uname=(EditText)findViewById(R.id.editText1);
            pwd=(EditText)findViewById(R.id.editText2);
            invalid=(TextView)findViewById(R.id.textView3);
            btnlog1=(Button)findViewById(R.id.button1);
            //btncancel1=(Button)findViewById(R.id.button2);
            //SERVICE_URL=ServerURL.URL+"/msd";
    
            btnlog1.setOnClickListener(new View.OnClickListener()
            {           
                @Override
                public void onClick(View v) 
                {
                    mUname=uname.getText().toString();
                    mPwd=pwd.getText().toString();
                    SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = prefs.edit();
                    editor.putString("EMP_ID",mUname);
                    editor.putString("EMP_PWD", mPwd);
                    editor.commit(); //important, otherwise it wouldn't save.
    //                  display("Login clicked");
                    if(!mUname.equalsIgnoreCase("") && !mPwd.equalsIgnoreCase(""))
                    {
                        cd = new ConnectionDetector(getApplicationContext());
                        isInternetPresent = cd.isConnectingToInternet();
                        //Toast.makeText(MainActivity.this, isInternetPresent, Toast.LENGTH_LONG).show();
                        if(isInternetPresent)
                        {
    
    
                        try
                        {
                            validat_user(mUname,mPwd);
    
                        }
                        catch(Exception e)
                        {
                            display("Network error.\nPlease check with your network settings.");
                            uname.setText("");
                            pwd.setText("");
                        }
                        }
                        else
                        {
                            display("No Internet Connection...");
                        }
    
                    }
                    else
                    {
                        invalid.setText("Please enter the data");
                    }
                }
            });
    
        }
        public void display(String msg) 
        {
            Toast.makeText(MainActivity.this, msg, Toast.LENGTH_LONG).show();
        }
    
    
        private void validat_user(String stg1, String stg2)
        {
            db_select=stg1;
            WebServiceTask wst = new WebServiceTask(WebServiceTask.POST_TASK, this, "Login in progress...");
    
            wst.addNameValuePair("EMP_ID", stg1);
            wst.addNameValuePair("EMP_PWD", stg2);
    
            wst.execute(new String[] { SERVICE_URL });
    
        }
        @SuppressWarnings("deprecation")
        public void no_net()
        {
            display( "No Network Connection");
            final AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
            alertDialog.setTitle("No Internet Connection");
            alertDialog.setMessage("You don't have internet connection.\nElse please check the Internet Connection Settings.");
            //alertDialog.setIcon(R.drawable.error_info);
            alertDialog.setCancelable(false);
            alertDialog.setButton("Close", new DialogInterface.OnClickListener() 
            {
                public void onClick(DialogInterface dialog, int which)
                {   
                    alertDialog.cancel();
                    MainActivity.this.finish();
                    System.exit(0);
                }
            });
            alertDialog.setButton2("Use Local DataBase", new DialogInterface.OnClickListener() 
            {
                public void onClick(DialogInterface dialog, int which)
                {
                    display( "Accessing local DataBase.....");
                    alertDialog.cancel();
                }
            });
            alertDialog.show();
        }
    
        private class WebServiceTask extends AsyncTask<String, Integer, String> {
    
            public static final int POST_TASK = 1;
    
            private static final String TAG = "WebServiceTask";
    
            // connection timeout, in milliseconds (waiting to connect)
            private static final int CONN_TIMEOUT =12000;
    
            // socket timeout, in milliseconds (waiting for data)
            private static final int SOCKET_TIMEOUT =12000;
    
            private int taskType = POST_TASK;
            private Context mContext = null;
            private String processMessage = "Processing...";
    
            private ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
    
            private ProgressDialog pDlg = null;
    
            public WebServiceTask(int taskType, Context mContext, String processMessage) {
    
                this.taskType = taskType;
                this.mContext = mContext;
                this.processMessage = processMessage;
            }
    
            public void addNameValuePair(String name, String value) {
    
                params.add(new BasicNameValuePair(name, value));
            }
    
            @SuppressWarnings("deprecation")
            private void showProgressDialog() {
    
                pDlg = new ProgressDialog(mContext);
                pDlg.setMessage(processMessage);
                pDlg.setProgressDrawable(mContext.getWallpaper());
                pDlg.setProgressStyle(ProgressDialog.STYLE_SPINNER);
                pDlg.setCancelable(false);
                pDlg.show();
    
            }
    
            @Override
            protected void onPreExecute() {
    
                showProgressDialog();
    
            }
    
            protected String doInBackground(String... urls) {
    
                String url = urls[0].toString();
                String result = "";
                HttpResponse response = doResponse(url);
                if (response == null) {
                    return result;
                } else {
    
                    try {
    
                        result = inputStreamToString(response.getEntity().getContent());
    
                    } catch (IllegalStateException e) {
                        Log.e(TAG, e.getLocalizedMessage(), e);
    
                    } catch (IOException e) {
                        Log.e(TAG, e.getLocalizedMessage(), e);
                    }
                    catch(Exception e)
                    {
                        Log.e(TAG, e.getLocalizedMessage(), e);
                    }
    
                }
    
                return result;
            }
    
            @Override
            protected void onPostExecute(String response) {
    
                handleResponse(response);
                pDlg.dismiss();
    
            }
    
            // Establish connection and socket (data retrieval) timeouts
            private HttpParams getHttpParams() {
    
                HttpParams htpp = new BasicHttpParams();
    
                HttpConnectionParams.setConnectionTimeout(htpp, CONN_TIMEOUT);
                HttpConnectionParams.setSoTimeout(htpp, SOCKET_TIMEOUT);
    
                return htpp;
            }
    
            private HttpResponse doResponse(String url) {
    
                // Use our connection and data timeouts as parameters for our
                // DefaultHttpClient
                HttpClient httpclient = new DefaultHttpClient(getHttpParams());
    
                HttpResponse response = null;
    
                try {
                    switch (taskType) {
    
                    case POST_TASK:
    
                        HttpPost httppost= new HttpPost(url);
                        httppost.setEntity(new UrlEncodedFormEntity(params));
                        response = httpclient.execute(httppost);
    
                        break;
                    }
                } 
                catch (Exception e) {
                //  display("Remote DataBase can not be connected.\nPlease check network connection.");
    
                    Log.e(TAG, e.getLocalizedMessage(), e);
                    return null;
    
                }
    
                return response;
            }
    
            private String inputStreamToString(InputStream is) {
    
                String line = "";
                StringBuilder total = new StringBuilder();
    
                // Wrap a BufferedReader around the InputStream
                BufferedReader rd = new BufferedReader(new InputStreamReader(is));
    
                try {
                    // Read response until the end
                    while ((line = rd.readLine()) != null) {
                        total.append(line);
                    }
                } catch (IOException e) {
                    Log.e(TAG, e.getLocalizedMessage(), e);
                }
                catch(Exception e)
                {
                    Log.e(TAG, e.getLocalizedMessage(), e);
                }
    
                // Return full string
                return total.toString();
            }
    
        }
        public void handleResponse(String response) 
    
        {    
        //display("Response:"+response);
            if(!response.equalsIgnoreCase(""))
            {
                JSONObject jso;
                try {
                    jso = new JSONObject(response);
    
    
                        String status = jso.getString("status");
                        int valid=jso.getInt("valid");
                  //     display("Welcome : "+UName);
                     if(valid>0)
                     {
                        if( status.equalsIgnoreCase("") || status==null ||  status.equalsIgnoreCase("Failed"))
                        {
                            invalid.setText("Invalid password");
                            //reset();
                            pwd.setText("");
                        }
                        else
                        {
                            //display(status);
                            intObj=new Intent(MainActivity.this,Design_Activity.class);
                            startActivity(intObj);
                            MainActivity.this.finish();     
                        }
    
                     }
                     else
                     {
                         invalid.setText("Invalid userid");
                         uname.setText("");
                     }
                    }
                catch (JSONException e1) {
    
                    Log.e(TAG, e1.getLocalizedMessage(), e1);
                }
                catch(Exception e)
                {
                    Log.e(TAG, e.getLocalizedMessage(), e);
                }
    
    
            }
            else
            {
                display("Could not able to reach Server!");
            }
    
    
        }
        public void reset()
        {
    
    
            pwd.setText("");
            uname.setText("");
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2015-09-07
      • 2023-03-25
      • 1970-01-01
      • 2012-12-26
      • 2014-09-25
      • 2013-04-14
      • 2014-11-20
      • 1970-01-01
      • 2019-03-12
      相关资源
      最近更新 更多