Android HTTP 服务

使用 HTTP 服务:

1.
Apache HttpClinet
Http GET
Http POST


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

HTTP GET 示例:

public class TestHttpGetMethod{
    public void get(){
        BufferedReader in = null;

        try{
            HttpClient client = new DefaultHttpClient();
            HttpGet request = new HttpGet();
            request.setURI("http://w26.javaeye.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:
HttpGet request = new HttpGet("http://www.baidu.com/s?wd=amos_tl");
client.execute(request);

 

HTTP POST 示例:

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 示例:


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.

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
public class HttpActivity extends Activity{
    @override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        Log.d(TAG, "httpactivity startup...");
        getHttpContent();
    }
   
    private void getHttpContent(){
        try{
            ApplicationEx app = (ApplicationEx)this.getApplication();
            HttpClient client = app.getHttpClient();
            HttpGet request = new HttpGet();
            request.setURI("http://w26.javaeye.com");
            HttpResponse response = client.excute(resquest);

            String page = EntityUtils.toString(response.getEntity());
            Log.i(TAG, page);
        }catch(Exception e){
             Log.e(TAG, e.toString());
        }
    }
 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值