how to use Get method for calling web services in android

安稳与你 提交于 2019-12-25 01:44:16

问题


In my program i am using postmethod to call the web services . But the web service is based on Get method .I dont know how to write the code for Get method.Please tell me the how to write the code for Get method to call web services.My code is shown below based on post method.

RestClient arc = new RestClient("http:.............."); arc.AddParam("search", msft);

Here i created a object to RestClient and adding parameters by calling AddParam method.The RestClient class is

public class AddSubRestClient {

private ArrayList <NameValuePair> params;
private ArrayList <NameValuePair> headers;
private InputStream instream;
private String url;

private int responseCode;
private String message;

private String response;

public String getResponse() {
    return response;
}
public InputStream inResponse() {
     return instream;
}
public String getErrorMessage() {
    return message;
}

public int getResponseCode() {
    return responseCode;
}

public AddSubRestClient(String url)
{
    this.url = url;
    params = new ArrayList<NameValuePair>();
    headers = new ArrayList<NameValuePair>();
}

public void AddParam(String name, String value)
{
    params.add(new BasicNameValuePair(name, value));
}

public void AddHeader(String name, String value)
{
    headers.add(new BasicNameValuePair(name, value));
}

public void Execute() throws Exception
{
   //Postmethod
    HttpPost request = new HttpPost(url);
    Log.e("in","rest client");
     //add headers
     for(NameValuePair h : headers)
     {
         request.addHeader(h.getName(), h.getValue());
     }

     if(!params.isEmpty()){
         UrlEncodedFormEntity p_entity = new UrlEncodedFormEntity(params,HTTP.UTF_8);
         request.setEntity(p_entity);
         Log.e("params",params.toString());
         Log.e("request",request.toString());
     }
         executeRequest(request, url);

    }


public void executeRequest(HttpUriRequest request, String url)
{
    HttpClient client = new DefaultHttpClient();
   HttpResponse httpResponse;

    try {
       httpResponse = client.execute(request);
       responseCode = httpResponse.getStatusLine().getStatusCode();
       message = httpResponse.getStatusLine().getReasonPhrase();
        HttpEntity entity = httpResponse.getEntity();
       if (entity != null) {
      intream = entity.getContent();
      response = convertStreamToString(instream);
      / Closing the input stream will trigger connection release
            instream.close();
        }

    } catch (ClientProtocolException e)  {
        client.getConnectionManager().shutdown();
        e.printStackTrace();
    } catch (IOException e) {
        client.getConnectionManager().shutdown();
        e.printStackTrace();
    }
}

private static String convertStreamToString(InputStream is) {

    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null;
    try {
        Log.e("in","try block");
        line = reader.readLine();
        Log.e("line",line);
        if(line==null)
        {
            Log.e("Line","is null");
        }
        else{
            Log.e("Line","is not null");
             sb.append(line );

        }
         } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            Log.e("line","close");
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}

}

so please tell me how to write the code for get method in place of post method or tell me the solution

Thank you in advance


回答1:


Will this work? I haven't tested this recently, but it worked perfectly for a school project I had a while back. It will return a JSONObject, but it can obviously be modified to meet your needs. Also note the parameter is the string of the URL that you're calling the GET on.

public static JSONObject connectSingle(String url)
        {
            HttpClient httpclient = new DefaultHttpClient();

            // Prepare a request object
            HttpGet httpget = new HttpGet(url); 

            // Execute the request
            HttpResponse response;
            try {
                response = httpclient.execute(httpget);

                // Get hold of the response entity
                HttpEntity entity = response.getEntity();
                // If the response does not enclose an entity, there is no need
                // to worry about connection release

                if (entity != null) 
                {

                    // A Simple JSON Response Read
                    InputStream instream = entity.getContent();
                    String result= convertStreamToString(instream);
                    instream.close();

                    // A Simple JSONObject Creation
                    JSONObject obj = new JSONObject(result);
                    return obj;
                }
                else
                    return null;

            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;
        }


来源:https://stackoverflow.com/questions/4524401/how-to-use-get-method-for-calling-web-services-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!