2010-12-24 4 views
0

Dans mon programme, j'utilise postmethod pour appeler les services Web. Mais le service Web est basé sur la méthode Get. Je ne sais pas comment écrire le code pour la méthode Get. S'il vous plaît dites-moi comment écrire le code pour Get méthode pour appeler les services web. Mon code est montré ci-dessous basé sur post method. RestClient arc = new RestClient ("http: ..............")Comment utiliser Get méthode pour appeler des services Web dans Android

; arc.AddParam ("recherche", msft);

Ici, je créé un objet à RESTClient et en ajoutant des paramètres en appelant AddParam method.The RESTClient classe est

AddSubRestClient public class {

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

}

donc s'il vous plaît me dire comment écrire le code pour obtenir la méthode à la place de la méthode de poste ou dites-moi la solution

Merci d'avance

Répondre

0

Est-ce que cela fonctionnera? Je n'ai pas testé cela récemment, mais ça a parfaitement fonctionné pour un projet d'école que j'avais il y a quelques temps. Il retournera un JSONObject, mais il peut évidemment être modifié pour répondre à vos besoins. Notez également que le paramètre est la chaîne de l'URL sur laquelle vous appelez le GET.

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

S'il vous plaît voir ma question connexe: http://stackoverflow.com/questions/30092261/using-volley-library-inside-a-library –

Questions connexes