Android JSON通过带标头的HTTPPOST调用

时间:2011-10-07 17:35:41

标签: java android json rest http-post

我找到了一个关于如何从Android中的HTTPPOST调用JSON的示例。现在我可以使用以下链接在我的localhost上调用A服务:(http://10.0.2.2/testingjson/testing.json)

它给出了listView中的输出,这很棒!

现在我需要或要求的是我想在链接上插入一些额外的信息,如

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

有两个java文件,Main和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;
    }
}

有没有完整的示例,我可以在这里学习如何在此示例中添加Header?或任何天才可以帮助我吗? :)

我愿意解决这个问题,所以我很乐意详细讨论解决这个问题! :)

如果需要更多信息,请告诉我。

提前致谢!

2 个答案:

答案 0 :(得分: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,它将允许你使用你发布的网址(http://10.0.0.2/some/url?param=123&otherparam=456)。你仍然可以用同样的方式阅读回复。

答案 1 :(得分:1)

我很想知道你是想把它放在查询字符串上还是在标题中。查询字符串变量将在URL的末尾(例如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"));