2011-10-07 41 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应用程序来执行此操作。 –