开发者

Android JSON Call through HTTPPOST with Headers

开发者 https://www.devze.com 2023-04-11 18:11 出处:网络
I found an example on how to call JSON from HTTPPOST in Android. Now I can call A service on my localhost using the link: (http://10.0.2.2/testingjson/testing.json)

I found an example on how to call JSON from HTTPPOST in Android. Now I can call A service on my localhost using the link: (http://10.0.2.2/testingjson/testing.json)

It gives the output in the listView and that is Great!

Now what I need or require is that I want to insert some extra information on the link like,

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

There are two java Files, Main and JSONfunction.

Here is all the code:

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 = JSONf开发者_开发技巧unctions.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(); 

            }
        });
    }
}

Now the Second File:

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

Is there any complete Example from where I can learn how to add Header in this example? or can any genius help me? :)

I am willing to solve this problem so I will be happy to talk in detail to solve this issue! :)

Please let me know if need more information..

Thanks in Advance!


If you truly want to use POST you need to create a NameValuePair object and populate it with your parameters.

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

But I suspect that since you are only GETting a JSON object you don't actually want to use HttpPost objects to make your request. Look at HttpGet instead which will allow you to use the url as you have posted (http://10.0.0.2/some/url?param=123&otherparam=456). You can still read the response the same way.


I am confused about whether you want to put this on the query string or in a header. A query string variable would go right at the end of the URL (e.g. http://10.0.2.2/testingjson/testing.json?regid=1234&pass="abcd")

As for headers looks like the HttpPost class has an inherited addHeader() method.

So it would go something like:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号