`
熊滔爱孟涛静
  • 浏览: 122026 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

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.    }  
分享到:
评论

相关推荐

    org.apache.http.httpentity jar包-系列jar包

    import org.apache.http.client.methods.HttpPost; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.ssl.SSLSocketFactory; import org.apache.http.impl.client.DefaultHttpClient; ...

    org.apache.http包

    import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.HttpVersion; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; ...

    org.apache.http jar包

    org.apache.http jar包 import org.apache.http.Header; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; import org....

    org.apache.http源代码和jar包

    import org.apache.http.Header; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; import org.apache.http.HttpResponse; import org....

    httppost和httpget需要的jar包

    httppost和httpget需要的jar包

    nginx-1.19.3-http-flv.zip

    2. 整体打包,已配置好nginx.conf的http-flv直播流,以及http web环境。无需任何配置即可使用 3. 自带windows的服务注册程序,使用如下方式,将nginx注册为windows的服务,实现无人值守维护管理 windows服务注册: 1...

    Http POST 调试\测试工具

    3、打开httppost.exe 即可运行本软件。 Jadder Http 测试工具 E-Mail: jadderbao@163.com 软件功能: ver 0.3 1、添加检测POST/GET返回内容格式,如为json格式就自动格式化显示 2、添加打开,保存文件时,自动...

    基于Labview的HTTP的GET与POST请求示例

    超文本传输协议(HTTP)的设计目的是保证客户机与服务器之间的通信。 HTTP 的工作方式是客户机与服务器之间的请求-应答协议。 web 浏览器可能是客户端,而计算机上的网络应用程序也可能作为服务器端。 举例:...

    nginx-http-flv-module(windows版)

    已编译好的nginx-http-flv-molule(windows版) 基于: --&gt; openssl-1.1.1g --&gt; pcre-8.44 --&gt; zlib-1.2.11 --&gt; nginx-http-module-v1.2.10 --&gt; nginx-1.21.6 ======================== 在网上查找半天都只有教程,...

    C++ 实现 HTTP HTTPS POST GET(包含curl版本和winhttp两种实现)

    C++ 实现 HTTP HTTPS POST GET(包含curl版本和winhttp两种实现)。 玩过抓包,网络协议分析的朋友肯定都知道http https post get,web端和用户的交互主要是通过post get完成的。 我这里有两种实现: 1:libcurl实现的...

    VC通过Http协议Get或Post方式与WebService通信,解析返回的Json

    本资源是一个封装类,采用异步方式解决了Wininet不能设置超时的问题,当前异步采用C++...MFC程序中通过HttpGet和HttpPost方式向WebService发送请求,WebService以Json的方式返回数据,MFC程序解析Json,得到指定数据。

    http 协议解析类 c++

    能够处理http协议:(1)解析 (2)构造http格式

    VC通过HttpGet和HttpPost方式与WebService通信,解析返回的Json

    MFC程序中通过HttpGet和HttpPost方式向WebService发送请求,WebService以Json的方式返回数据,MFC程序解析Json,得到指定数据。

    C语言实现的HTTP请求

    C语言实现的HTTP请求,重写Http协议,并发送http报送的源文件

    HTTP协议详解(真的很经典)

    目前在WWW中使用的是HTTP/1.0的第六版,HTTP/1.1的规范化工作正在进行之中,而且HTTP-NG(Next Generation of HTTP)的建议已经提出。 HTTP协议的主要特点可概括如下: 1.支持客户/服务器模式。 2.简单快速:客户向...

    httpcore-4.3.2.jar和httpmime-4.3.5.jar

    里面是httpcore-4.3.2.jar和httpmime-4.3.5.jar两个jar包,其它csdn资源居然还要积分,我无语了,现在把我下载到的免费提供给大家。

    android http通信demo

    android 当中涉及到网络编程的部分经常会用到http通信,同时android也为我么您提供了HttpUrlConnection接口和HttpClient接口,大大的方便了开发。Http通信又分为两种方式:get和post,get可以uoqu静态页面,传入参数...

    HTTP协议详解及RFC2616(HTTP)中文版

    HTTP协议详解 RFC2616(HTTP)中文版 pdf 格式,高清

    HTTP服务器+测试客户端(含源码)

    HTTP服务器+测试客户端(含源码) 介绍 * 里面已经搭建好简单http服务器框架,方便添加自定义的http协议数据处理。 * 轻量级的http服务器,简单实用(IIS是航空母舰,WCF过于复杂而且技术耦合大...)。 * Socket网络...

Global site tag (gtag.js) - Google Analytics