在Android中使用HTTP GET传递参数

在Android中使用HTTP GET传递参数,android,android-asynctask,http-get,Android,Android Asynctask,Http Get,在我的应用程序中的一个视图中,我有一个ListView,它使用Listadapter、JSON、PHP等来显示MySQL数据库中的数据。所有这些都是可行的,但我试图弄清楚(没有成功)我如何向PHP发送一个参数,这样我就可以检索不到所有的配置文件(在我的应用程序中)而我想要的则取决于用户id 这是构成HTTP的AsynTask代码: private class GetProfiles extends AsyncTask<String, Void, String>{ priva

在我的应用程序中的一个视图中,我有一个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;
            }        
        }

但是它不允许我使用。

您可以重载异步任务构造函数,并将键值参数传递给成员变量,然后在发送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;
}
私有类GetProfiles扩展异步任务{
私人对话;
私有字符串消息;
私有最终GetProfilesListener侦听器;
受保护的HashMapqueryStringParams;
/**
*方法来设置侦听器值。
*/
公共GetProfiles(GetProfilesListener侦听器,HashMapqueryStringParams){
this.listener=listener;
this.queryStringParams=queryStringParams;
}
受保护的void onPreExecute(){
super.onPreExecute();
pDialog=newprogressdialog(UserProfiles.this);
pDialog.setTitle(“联系服务器”);
pDialog.setMessage(“加载配置文件…”);
pDialog.setUndeterminate(假);
pDialog.setCancelable(真);
pDialog.show();
}
@凌驾
受保护的字符串doInBackground(字符串…参数){
if(params==null)
返回null;
字符串url=params[0];
//在这里,您可以使用您传递的queryString哈希映射参数
url+=“uid=“+queryStringParams.get(“uid”);//例如
试一试{
//创建http连接
HttpClient=new DefaultHttpClient();
HttpGet HttpGet=新的HttpGet(url);
//连接
HttpResponse response=client.execute(httpget);
//得到回应
HttpEntity=response.getEntity();
if(实体==null){
message=“服务器无响应”;
返回null;
}
//获取响应内容并将其转换为json字符串
InputStream=entity.getContent();
返回streamToString(is);
}
捕获(IOE异常){
message=“无网络连接”;
}
返回null;
}
因此,现在您可以在调用异步任务时发送参数,如下面的调用

    queryStringParams= new HashMap<String, String>();
    queryStringParams.put("UID", "12")
    new getListItems(listener, queryStringParams).execute(); 
queryStringParams=newhashmap();
queryStringParams.put(“UID”,“12”)
新建getListItems(侦听器、queryStringParams).execute();

希望这会有所帮助。

您也可以这样做:

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;
}
受保护的字符串addLocationToUrl(字符串url){
如果(!url.endsWith(“?”)
url+=“?”;
List params=new LinkedList();
如果(纬度=0.0&&lon!=0.0){
参数add(新的BasicNameValuePair(“lat”,String.valueOf(lat)));
参数add(新的BasicNameValuePair(“lon”,String.valueOf(lon)));
}
if(address!=null&&address.getPostalCode()!=null)
add(新的BasicNameValuePair(“postalCode”,address.getPostalCode());
if(address!=null&&address.getCountryCode()!=null)
add(新的BasicNameValuePair(“country”,address.getCountryCode());
参数add(新的BasicNameValuePair(“用户”,agent.uniqueId));
String paramString=URLEncodedUtils.format(params,“utf-8”);
url+=paramString;
返回url;
}
导入java.io.BufferedReader;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.InputStreamReader;
导入java.util.ArrayList;
导入org.apache.http.HttpResponse;
导入org.apache.http.NameValuePair;
导入org.apache.http.client.HttpClient;
导入org.apache.http.client.entity.UrlEncodedFormEntity;
导入org.apache.http.client.methods.HttpPost;
导入org.apache.http.impl.client.DefaultHttpClient;
导入org.apache.http.message.BasicNameValuePair;
导入org.apache.http.params.BasicHttpParams;
导入org.apache.http.params.HttpConnectionParams;
导入org.apache.http.params.HttpParams;
导入org.json.JSONException;
导入org.json.JSONObject;
导入android.app.Activity;
导入android.app.AlertDialog;
导入android.app.ProgressDialog;
导入android.content.Context;
导入android.content.DialogInterface;
导入android.content.Intent;
导入android.content.SharedReferences;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.util.Log;
导入android.view.view;
导入android.widget.Button;
导入android.widget.EditText;
导入android.widget.TextView;
导入android.widget.Toast;
公共类MainActivity扩展了活动
{
公共编辑文本uname,pwd;
按钮btnlog1;
文本视图无效;
公共按钮BTNCENCEL1;
公共字符串db_select;
字符串名称;
字符串mPwd;
字符串温度;
意图输入北京;
意向=无效;
布尔值isInternetPresent=false;
连接检测器cd;
专用字符串服务\u URL=”http://10.54.3.208:8080";
私有最终字符串TAG=“MainActivity”;
公共静态最终字符串PREFS\u NAME=“MyPrefsFile”;
@凌驾
创建时受保护的void(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
MainActivity.this.setContentView(R.layout.activity_main);
uname=(EditText)findViewById(R.id.editText1);
pwd=(EditText)findViewById(R.id.editText2);
无效=(TextView)findViewById(R.id.textView3);
btnlog1=(按钮)findViewById(R.id.button1);
//BTNCENCEL1=(按钮)findViewById(R.id.button2);
//服务URL=ServerURL.URL+“/msd”;
btnlog1.setOnClickListener(新视图.OnClickListener()
{           
@凌驾
公共void onClick(视图v)
{
mUname=uname.getText().toString();
mPwd=pwd.getText().toString();
SharedReferences prefs=GetSharedReferences(prefs\u名称,Context.MODE\u PRIVATE);
SharedReferences.Editor edi
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;
}
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("");
    }

}