簡體   English   中英

從Android發送帶有參數的json Http請求

[英]Sending a json Http request with parameters from Android

閱讀一些教程后,我可以使用php從MySql數據庫中獲取訂單列表,並顯示在我的Android應用中。 我需要通過userId過濾此列表(useid保存在首選項中)。 我必須發送帶有參數“ userId”的http請求,但我不知道如何。 我現在擁有的代碼:

public class JSONfunctions {

public static JSONObject getJSONfromURL(String url){
    InputStream is = null;
    String result = "";
    JSONObject jArray = null;

    //http post
    try{
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

    }catch(Exception e){
            Log.e("log_tag", "Error in http connection "+e.toString());
    }

  //convert response to string
    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();
            result=sb.toString();
    }catch(Exception e){
            Log.e("log_tag", "Error converting result "+e.toString());
    }

    try{

        jArray = new JSONObject(result);            
    }catch(JSONException e){
            Log.e("log_tag", "Error parsing data "+e.toString());
    }

    return jArray;
}    
}

對於訂單列表:

public class Masuratori extends ListActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.listplaceholder);

    ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();


    JSONObject json = JSONfunctions.getJSONfromURL("http://MySite/masuratori.php");

    try{

        JSONArray  earthquakes = json.getJSONArray("earthquakes");

        for(int i=0;i<earthquakes.length();i++){                        
            HashMap<String, String> map = new HashMap<String, String>();    
            JSONObject e = earthquakes.getJSONObject(i);

            map.put("id",  String.valueOf(i));
            map.put("name", e.getString("clie"));
            map.put("magnitude",  e.getString("userid"));
            map.put("adresa",  e.getString("adr"));
            map.put("detalii",  e.getString("det"));
            mylist.add(map);            
        }       
    }catch(JSONException e)        {
         Log.e("log_tag", "Error parsing data "+e.toString());
    }

    ListAdapter adapter = new SimpleAdapter(this, mylist , R.layout.activity_masuratori, 
                    new String[] { "name", "adresa","detalii","magnitude"}, 
                    new int[] { R.id.item_title, R.id.item_subtitle, R.id.item_subtitle2, R.id.item_subtitle3 });

    setListAdapter(adapter);

    final ListView lv = getListView();
    lv.setTextFilterEnabled(true);  
    lv.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {              
            @SuppressWarnings("unchecked")
            HashMap<String, String> o = (HashMap<String, String>) lv.getItemAtPosition(position);                   
            Toast.makeText(Masuratori.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_SHORT).show(); 

        }
    });
}
}

我從首選項中收到用戶ID值:

public class Calculator extends Activity {
TextView prefEditText;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_calculator);
    prefEditText= (TextView)findViewById(R.id.textUser);        
    loadPref();
    prefEditText= (TextView)findViewById(R.id.prefEditText);
    loadPref();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.calculator, menu);
    return true;
}
@Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  // TODO Auto-generated method stub
  //super.onActivityResult(requestCode, resultCode, data);

  loadPref();
 }

 private void loadPref(){
  SharedPreferences mySharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);


  String my_edittext_preference = mySharedPreferences.getString("edittext_preference", "");
     prefEditText.setText(my_edittext_preference);

 }          
}

execute() HttpPost ,可以使用以下代碼添加參數:

// Add userId parameter
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);  
nameValuePairs.add(new BasicNameValuePair("userId", "12345"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

由於您僅發送一個參數,為什么不在查詢字符串中發送它。

String userId = getUserId();
JSONObject json = JSONfunctions.getJSONfromURL("http://MySite/masuratori.php?userId=" + userId);

然后您在php中檢索它

$userId = $_GET['userId']

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM