Http

使用 HTTP 服务:

1.
Apache HttpClinet
Http GET
Http POST


a.创建 HttpClient
b.初始 HTTP GET 方法或 POST 方法.
c.设置参数 键值对
d.执行 HTTP 调用
e.处理 HTTP 回复

HTTP GET 示例:

Java代码
  1. public class TestHttpGetMethod{   
  2.     public void get(){   
  3.         BufferedReader in = null;   
  4.   
  5.         try{   
  6.             HttpClient client = new DefaultHttpClient();   
  7.             HttpGet request = new HttpGet();   
  8.             request.setURI("http://w26.iteye.com");   
  9.             HttpResponse response = client.execute(request);   
  10.                
  11.             in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));      
  12.             StringBuffer sb = new StringBuffer("");    
  13.             String line = "";   
  14.             String NL = System.getProperty("line.separator");   
  15.             while((line = in.readLine()) != null){   
  16.                 sb.append(line + NL);   
  17.             }   
  18.             in.close();   
  19.             String page = sb.toString();   
  20.   
  21.             Log.i(TAG, page);   
  22.   
  23.   
  24.   
  25.         }catch(Exception e){   
  26.             Log.e(TAG,e.toString())   
  27.         }finally{   
  28.             if(in != null){   
  29.                 try{   
  30.                     in.close();   
  31.                 }catch(IOException ioe){   
  32.                     Log.e(TAG, ioe.toString());   
  33.                 }   
  34.             }   
  35.   
  36.         }   
  37.     }   
  38. }  
public class TestHttpGetMethod{
    public void get(){
        BufferedReader in = null;

        try{
            HttpClient client = new DefaultHttpClient();
            HttpGet request = new HttpGet();
            request.setURI("http://w26.iteye.com");
            HttpResponse response = client.execute(request);
            
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));   
            StringBuffer sb = new StringBuffer(""); 
            String line = "";
            String NL = System.getProperty("line.separator");
            while((line = in.readLine()) != null){
                sb.append(line + NL);
            }
            in.close();
            String page = sb.toString();

            Log.i(TAG, page);



        }catch(Exception e){
            Log.e(TAG,e.toString())
        }finally{
            if(in != null){
                try{
                    in.close();
                }catch(IOException ioe){
                    Log.e(TAG, ioe.toString());
                }
            }

        }
    }
}




带参数的 HTTP GET:

Java代码
  1. HttpGet request = new HttpGet("http://www.baidu.com/s?wd=amos_tl");   
  2. client.execute(request);  
HttpGet request = new HttpGet("http://www.baidu.com/s?wd=amos_tl");
client.execute(request);



HTTP POST 示例:

Java代码
  1. public class TestHttpPostMethod{   
  2.     public void post(){   
  3.         BufferedReader in = null;   
  4.   
  5.         try{   
  6.             HttpClient client = new DefaultHttpClient();   
  7.             HttpPost request = new HttpPost("http://localhost/upload.jsp");   
  8.   
  9.             List<NameValuePair> postParams = new ArrayList<NameValuePair>();   
  10.             postParams.add(new BasicNameValuePair("filename""sex.mov"));   
  11.                
  12.             UrlEncodeFormEntity formEntity = new UrlEncodeFormEntity(postParams);   
  13.             request.setEntity(formEntity);   
  14.                
  15.             HttpResponse response = client.execute(request);   
  16.   
  17.             in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));      
  18.             StringBuffer sb = new StringBuffer("");    
  19.             String line = "";   
  20.             String NL = System.getProperty("line.separator");   
  21.             while((line = in.readLine()) != null){   
  22.                 sb.append(line + NL);   
  23.             }   
  24.             in.close();   
  25.             String result = sb.toString();   
  26.             Log.i(TAG, result );   
  27.   
  28.         }catch(Exception e){   
  29.             Log.e(TAG,e.toString())   
  30.         }finally{   
  31.             if(in != null){   
  32.                 try{   
  33.                     in.close();   
  34.                 }catch(IOException ioe){   
  35.                     Log.e(TAG, ioe.toString());   
  36.                 }   
  37.             }   
  38.   
  39.         }   
  40.     }   
  41. }  
public class TestHttpPostMethod{
    public void post(){
        BufferedReader in = null;

        try{
            HttpClient client = new DefaultHttpClient();
            HttpPost request = new HttpPost("http://localhost/upload.jsp");

            List<NameValuePair> postParams = new ArrayList<NameValuePair>();
            postParams.add(new BasicNameValuePair("filename", "sex.mov"));
            
            UrlEncodeFormEntity formEntity = new UrlEncodeFormEntity(postParams);
            request.setEntity(formEntity);
            
            HttpResponse response = client.execute(request);

            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));   
            StringBuffer sb = new StringBuffer(""); 
            String line = "";
            String NL = System.getProperty("line.separator");
            while((line = in.readLine()) != null){
                sb.append(line + NL);
            }
            in.close();
            String result = sb.toString();
            Log.i(TAG, result );

        }catch(Exception e){
            Log.e(TAG,e.toString())
        }finally{
            if(in != null){
                try{
                    in.close();
                }catch(IOException ioe){
                    Log.e(TAG, ioe.toString());
                }
            }

        }
    }
}






multipart POST 支持:

需要以下支持:
Commons IO
http://commons.apache.org/io/

Mime4j
http://james.apache.org/mime4j/

HttpMime
http://hc.apache.org/httpcomponents-client/httpmime/index.html

下载全部JAR网址:
http://www.sayedhashimi.com/downloads/android/multipart-android.zip



multipart POST 示例:

Java代码
  1.   
  2. public class TestHttpMultipartPost{   
  3.     public void mulPost(){   
  4.     try{   
  5.         InputStram in = this.getAssets().open("data.xml");     
  6.         HttpClient client = new HttpDefaultHttpClient();   
  7.         HttpPost request = new HttpPost("http://localhost/upload.jsp");   
  8.         byte[] data = IOUtils.toByteArray(in);   
  9.         InputStreamBody isb = new InputStreamBody(new ByteArrayIntputStream(data), "uploadedFile");    
  10.         StringBody sb1 = new StringBody("some text");         
  11.         StringBoyd sb2 = new StringBody("some text too");   
  12.   
  13.         MultipartEntity me = new MultipartEntity();   
  14.         me.addPart("uploadedFile", isb);   
  15.         me.addPart("one" ,sb1);   
  16.         me.addPart("two" ,sb2);   
  17.     
  18.         request.setEntity(me);   
  19.         HttpRespones response = client.excute(request);   
  20.         res.getEntity().getContent().close();   
  21.            
  22.     } catch(Throwable e){   
  23.         Log.e(TAG, e.toString());   
  24.     }   
  25.   
  26.     }   
  27.   
  28. }  
public class TestHttpMultipartPost{
    public void mulPost(){
    try{
        InputStram in = this.getAssets().open("data.xml");  
        HttpClient client = new HttpDefaultHttpClient();
        HttpPost request = new HttpPost("http://localhost/upload.jsp");
        byte[] data = IOUtils.toByteArray(in);
        InputStreamBody isb = new InputStreamBody(new ByteArrayIntputStream(data), "uploadedFile"); 
        StringBody sb1 = new StringBody("some text");      
        StringBoyd sb2 = new StringBody("some text too");

        MultipartEntity me = new MultipartEntity();
        me.addPart("uploadedFile", isb);
        me.addPart("one" ,sb1);
        me.addPart("two" ,sb2);
 
        request.setEntity(me);
        HttpRespones response = client.excute(request);
        res.getEntity().getContent().close();
        
    } catch(Throwable e){
        Log.e(TAG, e.toString());
    }

    }

}


异常处理
    重试处理

多线程问题
    使用 ClientConnectionManager ,创建一个线程安全的 HttpClient.

Java代码
  1. public class ApplicationEx extends Application{   
  2.     public static final String TAG = "amos_tl";   
  3.     private HttpClient client = null;   
  4.   
  5.     @override  
  6.     public void onCreate(){   
  7.         super.onCreate();   
  8.         client = createHttpClient();   
  9.     }   
  10.   
  11.     @override    
  12.     public void onLowMemory(){   
  13.         super.onLowMemory();   
  14.         shutdownHttpClient();   
  15.     }   
  16.   
  17.     @override  
  18.     public void onTerminate(){   
  19.         super.onTerminate();   
  20.         shutdownHttpClient();   
  21.     }   
  22.   
  23.     private void shutdownHttpClient(){   
  24.         if(client != null && client.getConnectionManager() != null){   
  25.             client.getConnectionManager().shutdown();   
  26.             client = null;   
  27.         }   
  28.     }   
  29.        
  30.     private HttpClient createHttpClient(){   
  31.         Log.d(TAG, "create httpclient ...");   
  32.         HttpParams params = new BasicHttpParams();   
  33.         HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);   
  34.         HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET);   
  35.         HttpProtocolParams.setUseExpectContinue(params, true);   
  36.         SchemaRegistry sr = new SchemaRegistry();   
  37.         sr.register(new Schema("http", PlainSocketFactory.getSocketFactory(), 80));   
  38.         sr.register(new Schema("https", SLLSocketFactory.getSocketFactory(), 443));   
  39.         ClientConnectionManager cm = new ThreadSafeClientConnManager(params, sr);   
  40.   
  41.         return new DefaultHttpClient(cm, params);   
  42.     }       
  43.   
  44.     public HttpClient getHttpClient(){   
  45.         return client;   
  46.     }   
  47.        
  48.         
  49. }  
public class ApplicationEx extends Application{
    public static final String TAG = "amos_tl";
    private HttpClient client = null;

    @override
    public void onCreate(){
        super.onCreate();
        client = createHttpClient();
    }

    @override 
    public void onLowMemory(){
        super.onLowMemory();
        shutdownHttpClient();
    }

    @override
    public void onTerminate(){
        super.onTerminate();
        shutdownHttpClient();
    }

    private void shutdownHttpClient(){
        if(client != null && client.getConnectionManager() != null){
            client.getConnectionManager().shutdown();
            client = null;
        }
    }
    
    private HttpClient createHttpClient(){
        Log.d(TAG, "create httpclient ...");
        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.DEFAULT_CONTENT_CHARSET);
        HttpProtocolParams.setUseExpectContinue(params, true);
        SchemaRegistry sr = new SchemaRegistry();
        sr.register(new Schema("http", PlainSocketFactory.getSocketFactory(), 80));
        sr.register(new Schema("https", SLLSocketFactory.getSocketFactory(), 443));
        ClientConnectionManager cm = new ThreadSafeClientConnManager(params, sr);

        return new DefaultHttpClient(cm, params);
    }    

    public HttpClient getHttpClient(){
        return client;
    }
    
     
}


HttpActivity.java

Java代码
  1. public class HttpActivity extends Activity{   
  2.     @override  
  3.     public void onCreate(Bundle savedInstanceState){   
  4.         super.onCreate(savedInstanceState);   
  5.         Log.d(TAG, "httpactivity startup...");   
  6.         getHttpContent();   
  7.     }   
  8.        
  9.     private void getHttpContent(){   
  10.         try{   
  11.             ApplicationEx app = (ApplicationEx)this.getApplication();   
  12.             HttpClient client = app.getHttpClient();   
  13.             HttpGet request = new HttpGet();   
  14.             request.setURI("http://w26.iteye.com");   
  15.             HttpResponse response = client.excute(resquest);   
  16.   
  17.             String page = EntityUtils.toString(response.getEntity());   
  18.             Log.i(TAG, page);   
  19.         }catch(Exception e){   
  20.              Log.e(TAG, e.toString());   
  21.         }    
  22.     }   
  23.   
  24.   
  25.    }  

你可能感兴趣的:(apache,多线程,android,jsp,ITeye)