通过在Android中将参数传递给url来检索数据

时间:2013-12-29 14:48:15

标签: java android json httprequest httpresponse

我需要的是将一个参数附加到网址以检索数据&我正在使用json解析器。在我不必传递参数的情况下获得完美的结果。但是无法弄清楚如何将像String ID这样的参数传递给url来检索数据。

     //Inside JSON Response calling class

  JSONParser jParser = new JSONParser();

            JSONArray jArraySearchJob = jParser.getJSONFromUrl(url_Jobsearch);

            try{

                for (int i = 0; i < jArraySearchJob.length(); i++) 
                {
            JSONObject jsonElements = jArraySearchJob.getJSONObject(i);

            String J_p_id    = jsonElements.getString(android_J_P_ID);

        HashMap<String, String> hashAmbJobSearch = new HashMap<String, String>();

                    // adding each child node to HashMap key

                    hashAmbJobSearch.put(android_J_P_ID, J_p_id);

                    // adding HashList to ArrayList

                    ResultList_JobSearch.add(hashAmbJobSearch);
                }

Json Parser:

public class JSONParser {

    static InputStream is = null;

    static JSONArray jarray = null;

    static String json = "";

    //Method Returns JSON

    public JSONArray getJSONFromUrl(String url) {               

            StringBuilder builder = new StringBuilder();

            HttpClient client = new DefaultHttpClient();

            HttpPost httppost = new HttpPost(url);
         try {
              HttpResponse response = client.execute(httppost);

              StatusLine statusLine = response.getStatusLine();

              int statusCode = statusLine.getStatusCode();

              if (statusCode == 200) 
              {
                HttpEntity entity = response.getEntity();

                InputStream content = entity.getContent();

                BufferedReader reader = new BufferedReader(new InputStreamReader(content));

                String line;

                while ((line = reader.readLine()) != null) 
                {
                  builder.append(line);
                }
              } 
              else
              {
                  Log.e("==>", "Failed to download file");
              }
            } 

         catch (ClientProtocolException e) 
            {
                e.printStackTrace();
            }

         catch (IOException e) 
            {
                e.printStackTrace();
            }

        // try parse the string to a JSON object
        try 
        {
            jarray = new JSONArray(builder.toString());
        } 

        catch (JSONException e) 
            {
                Log.e("JSON Parser", "Error parsing data " + e.toString());
            }

        // return JSON String
        return jarray;
    }
}

1 个答案:

答案 0 :(得分:3)

通常用户名和密码作为参数发送

http://www.sample.url?Username=userNameValue&Password=passwordvalue

如果是安卓。

1.For get method as query params

String url = http://www.sample.url?username=+ Uri.encode(UserName) + "&password=" + Uri.encode(password)

HttpGet get = new HttpGet(url);

2. For post mehod as postparam in querystring (query params is again same as get method only)

3. If you want send as postparams use below code 


        ArrayList<NameValuePair> projectLoginInfo = new ArrayList<NameValuePair>();
        projectLoginInfo.add(new BasicNameValuePair("username", userNameValue));
        projectLoginInfo.add(new BasicNameValuePair("password", passwordValue));
         HttpPost httppost = new HttpPost("http://www.sample.url");

         try{      //encode login data and Hands the entity to the request.
            httppost.setEntity(new UrlEncodedFormEntity(projectLoginInfo));
        }
        catch (UnsupportedEncodingException e1)
        {
            e1.printStackTrace();
            Log.e("UnsupportedEncoding", "unable to encode some characters", e1);

            return -1;
        }`

您应该在Json Parser类中使用以下代码

ArrayList<NameValuePair> projectLoginInfo = new ArrayList<NameValuePair>();
    projectLoginInfo.add(new BasicNameValuePair("username", userNameValue));
    projectLoginInfo.add(new BasicNameValuePair("password", passwordValue));
     HttpPost httppost = new HttpPost("http://www.sample.url");

     try{      //encode login data and Hands the entity to the request.
        httppost.setEntity(new UrlEncodedFormEntity(projectLoginInfo));
    }
    catch (UnsupportedEncodingException e1)
    {
        e1.printStackTrace();
        Log.e("UnsupportedEncoding", "unable to encode some characters", e1);

        return null;
    }`
          HttpResponse response = client.execute(httppost);
          StatusLine statusLine = response.getStatusLine();