2013-01-01 187 views
0

我正在從Android調用其他Web服務。 Web服務代碼如下在調用其他Web服務時處理服務器故障

@Path("test") 
public class Test 
{ 

    @GET 
    @Path("name/{name}") 
    @Produces(MediaType.TEXT_PLAIN) 
    public Response say(@PathParam("name") String name) 
    { 
     //return "Hello ......"+name; 
     ResponseBuilder response = Response.ok((Object)"Hello ......"+name); 
     return response.build(); 
    } 
} 

Android客戶端代碼如下

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.net.URLEncoder; 
import java.security.KeyStore; 
import java.util.ArrayList; 

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.HttpVersion; 
import org.apache.http.NameValuePair; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.entity.UrlEncodedFormEntity; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.client.methods.HttpUriRequest; 
import org.apache.http.conn.ClientConnectionManager; 
import org.apache.http.conn.scheme.PlainSocketFactory; 
import org.apache.http.conn.scheme.Scheme; 
import org.apache.http.conn.scheme.SchemeRegistry; 
import org.apache.http.conn.ssl.SSLSocketFactory; 
import org.apache.http.impl.client.DefaultHttpClient; 
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; 
import org.apache.http.message.BasicNameValuePair; 
import org.apache.http.params.BasicHttpParams; 
import org.apache.http.params.HttpParams; 
import org.apache.http.params.HttpProtocolParams; 
import org.apache.http.protocol.HTTP; 

import android.util.Log; 

public class RestClient { 

    private static final int GET = 1; 
    private static final int POST = 2; 
    private ArrayList <NameValuePair> params; 
    private ArrayList <NameValuePair> headers; 

    private String url; 

    private int responseCode; 
    private String message; 

    private String response; 

    public String getResponse() { 
     return response; 
    } 

    public String getErrorMessage() { 
     return message; 
    } 

    public int getResponseCode() { 
     return responseCode; 
    } 

    public RestClient(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(int selection) throws Exception 
    { 
     switch(selection) { 
      case GET: 
      { 
       //add parameters 
       String combinedParams = ""; 
       if(!params.isEmpty()){ 
        combinedParams += "?"; 
        for(NameValuePair p : params) 
        { 
         String paramString = p.getName() + "=" + URLEncoder.encode(p.getValue(),"UTF-8"); 
         if(combinedParams.length() > 1) 
         { 
          combinedParams += "&" + paramString; 
         } 
         else 
         { 
          combinedParams += paramString; 
         } 
        } 
       } 

       HttpGet request = new HttpGet(url + combinedParams); 

       //add headers 
       for(NameValuePair h : headers) 
       { 
        request.addHeader(h.getName(), h.getValue()); 
       } 
       Log.d("prabhu","url......"+url + combinedParams); 
       Log.d("prabhu","request......"+request); 
       executeRequest(request, url); 
       break; 
      } 
      case POST: 
      { 
       HttpPost request = new HttpPost(url); 

       //add headers 
       for(NameValuePair h : headers) 
       { 
        request.addHeader(h.getName(), h.getValue()); 
       } 

       if(!params.isEmpty()){ 
        request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8)); 
       } 

       executeRequest(request, url); 

       Log.d("prabhu","url......"+url); 
       break; 
      } 
     } 
    } 

    private void executeRequest(HttpUriRequest request, String url) 
    { 


     HttpClient client = null; 

     try 
     { 

      KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); 
      trustStore.load(null, null); 

      SSLSocketFactory sf = new MySSLSocketFactory(trustStore); 
      sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); 

      HttpParams params = new BasicHttpParams(); 
      HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); 
      HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); 

      SchemeRegistry registry = new SchemeRegistry(); 
      registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); 
      registry.register(new Scheme("https", sf, 443)); 

      ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry); 
      client = new DefaultHttpClient(ccm, params); 
     }catch(Exception e) 
     { 

     } 

     HttpResponse httpResponse; 

     try { 
      httpResponse = client.execute(request); 
      responseCode = httpResponse.getStatusLine().getStatusCode(); 
      message = httpResponse.getStatusLine().getReasonPhrase(); 

      HttpEntity entity = httpResponse.getEntity(); 

      if (entity != null) { 

       InputStream instream = 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 { 
      while ((line = reader.readLine()) != null) { 
       sb.append(line + "\n"); 
      } 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } finally { 
      try { 
       is.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
     return sb.toString(); 
    } 
} 

使用上面的類,我打電話URL(網絡服務),如下面

RestClient client = new RestClient("http://localhost:8080/TestProject/test/name/madhu"); 


       try { 
        client.Execute(GET) 
       } catch (Exception e) { 
        e.printStackTrace(); 
       } 

       String response = client.getResponse(); 

如果服務器正在運行,每件事情都很好。但是,如果服務器停機,該如何處理這種情況。

回答

1

我認爲加上連接插座超時Http Request做的伎倆,

HttpParams httpParameters = new BasicHttpParams(); 
// Set the timeout in milliseconds until a connection is established. 
int timeoutConnection = 3000; 
HttpConnectionParams.setConnectionTimeout(httpParameters,timeoutConnection); 
// Set the default socket timeout (SO_TIMEOUT) 
// in milliseconds which is the timeout for waiting for data. 
int timeoutSocket = 3000; 
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket); 
+0

如果我添加連接和Socket超時的HTTP請求,那麼該如何使用'捕捉處理它 –

+0

(SocketTimeoutExceptionË )'..或'catch(IOException e)'。 – user370305

+0

明白了。感謝您的快速回復。 –