2011-10-07 74 views
0

我發現了一個關於如何從Android的HTTPPOST調用JSON的例子。現在我可以使用以下鏈接在我的本地主機上調用A服務:(http://10.0.2.2/testingjson/testing.json)Android JSON通過帶頭的HTTPPOST調用

它給出了listView中的輸出結果,這太棒了!

現在我需要什麼,或者需要的是,我要插入鏈接像一些額外的信息,

http://10.0.2.2/testingjson/testing.json?regid=1234&pass="abcd" 

有兩個java文件,主要和JSONfunction。

這裏是所有代碼:

Main.java:

package com.android.jsontut; 

    import java.util.ArrayList; 
    import java.util.HashMap; 

    import org.json.JSONArray; 
    import org.json.JSONException; 
    import org.json.JSONObject; 
    import org.w3c.dom.Document; 
    import org.w3c.dom.Element; 
    import org.w3c.dom.NodeList; 



    import android.app.ListActivity; 
    import android.content.Intent; 
    import android.os.Bundle; 
    import android.util.Log; 
    import android.view.View; 
    import android.widget.AdapterView; 
    import android.widget.AdapterView.OnItemClickListener; 
    import android.widget.ListAdapter; 
    import android.widget.ListView; 
    import android.widget.SimpleAdapter; 
    import android.widget.Toast; 

public class Main extends ListActivity { 
    /** Called when the activity is first created. */ 
    @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://10.0.2.2/testingjson/testing.json"); 

     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", "Earthquake name:" + e.getString("eqid")); 
       map.put("magnitude", "Magnitude: " + e.getString("magnitude")); 
       mylist.add(map);    
      }  
     }catch(JSONException e)  { 
      Log.e("log_tag", "Error parsing data "+e.toString()); 
     } 

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

     setListAdapter(adapter); 

     final ListView lv = getListView(); 
     lv.setTextFilterEnabled(true); 
     lv.setOnItemClickListener(new OnItemClickListener() { 
      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(Main.this, "ID '" + o.get("id") + "' was clicked.", Toast.LENGTH_SHORT).show(); 

      } 
     }); 
    } 
} 

現在第二個文件:

JSONFUNCTIONS.java

package com.android.jsontut; 

import java.io.BufferedReader; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.util.HashMap; 
import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
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.json.JSONArray; 
import org.json.JSONException; 
import org.json.JSONObject; 

import android.util.Log; 

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; 
    } 
} 

是否有完整的例子,從在這裏我可以學習如何添加標題?或者任何天才都能幫助我? :)

我願意解決這個問題,所以我會很樂意詳細地討論解決這個問題! :)

請讓我知道,如果需要更多的信息.​​.

先謝謝了!

回答

1

如果你真的想使用POST,你需要創建一個NameValuePair對象並用你的參數填充它。

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
    nameValuePairs.add(new BasicNameValuePair("regid", "123")); 
    nameValuePairs.add(new BasicNameValuePair("pass", "abcd")); 
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

但我懷疑,因爲你只得到一個JSON對象,你實際上並不希望使用HttpPost對象,使您的要求。看看HttpGet,它會允許你使用你發佈的url(http://10.0.0.2/some/url?param=123 & otherparam = 456)。您仍然可以以相同的方式閱讀回覆。

+0

謝謝! 我想使用HTTPOST,因爲它是安全的。 這是一個簡單的例子,但我被要求做的是使用HTTPPOST並使用標題。 請問你能提一下,在我的例子中,我可以在哪裏添加上面的代碼? :) – user712051

1

我很困惑你是否想把它放在查詢字符串或標題中。查詢字符串變量會去正確的網址(例如http://10.0.2.2/testingjson/testing.json?regid=1234&pass=「ABCD」)

至於頭看起來像HttpPost類有一個繼承addHeader()方法的結束。

所以它會去是這樣的:

HttpClient httpclient = new DefaultHttpClient(); 
HttpPost httppost = new HttpPost(url); 
httpPost.addHeader(new BasicHeader("regid", "1234")); 
+0

謝謝!是否有任何服務可以發送標題並獲得響應以測試我的程序? 我想使用HTTPPost,工作將會像..用戶將被要求寫出註冊ID和密碼,這個註冊ID和密碼將被請求到web服務,然後服務會迴應是或否。 – user712051

+0

I想使用Header not Query字符串。 – user712051

+0

我不知道任何與您的請求標題相符的Web服務。您可能必須編寫自己的小型Web應用程序來執行此操作。 –