http, get, post, HttpClient

http://www.blogjava.net/willpower88/archive/2008/04/14/192720.html

http://www.blogjava.net/willpower88/archive/2008/04/14/192679.html

http://lavasoft.blog.51cto.com/62575/168276/

玩法一:纯java,发送http get/post 请求,how?

客户端:发送请求

给个url,从url里获取connection出来,在connection上为所欲为,进行各种参数的设置(例如Keep-Alive, Content-Type, useCaches, doOutput等)。设置完后,该往连接上写东西了,我的outputstreamwriter已经蓄势待发,往哪里写呢?connection给你个口子。写完后,osw关掉,连接也关掉。

服务器端:接收请求

request里获取数据即可。

 

整个逻辑就是这么简单。

 

玩法二:HttpClient,开源项目,化了个妆,看着更舒心

 

变出一个client,给它设置目标服务器地址与端口。

变出一个方法(get/post)。

客户端执行方法。

方法会返回 服务器状态,及服务器返回信息,当然方法还要负责释放连接。注意,是方法完成的,不是client,client只负责“管理”方法,具体执行还是方法自己来。

需要提一下下:

1) get(读)总是那么简单,给?xx&xx这样的参数即可,post(删查改)需要NameValuePair这样的方式把参数设置进来。

2) 需要简单的userName/password验证也没关系,直接当post参数一并传过去好了;

3) 需要直接传xml文件也没关系,同2)

4) 多线程环境 下使用,需要给client来一个多线程的大管家MultiThreadedHttpConnectionManager

 

one little demo:

    public static void main(String[] args) throws HttpException, IOException {
        testHttp(0);
        testHttp(1);
    }
    
    /**
     * type=0, get
     * type=1, post
     * http://haoma.imobile.com.cn/index.php?mob=18858111994
     */
    public static void testHttp(int type) throws HttpException, IOException{
        HttpClient client = new HttpClient();
        client.getHostConfiguration().setHost("haoma.imobile.com.cn", 80, "http");
        HttpMethod method = null;
        switch(type){
        case 0:
            method = getGetMethod();
            break;
        case 1:
            method = getPostMethod();
            break;
        }
        
        client.executeMethod(method);
        System.out.println("statusLine = " + method.getStatusLine());

        String response = new String(method.getResponseBodyAsString());
        System.out.println("response = " + response);
        
        method.releaseConnection();
    }

    private static HttpMethod getGetMethod() {
        return new GetMethod("/index.php?mob=18858111994");
    }

    private static HttpMethod getPostMethod() {
        PostMethod post = new PostMethod("/index.php");
        NameValuePair simcard = new NameValuePair("mob", "18858111994");
        post.setRequestBody(new NameValuePair[] { simcard });
        return post;
    }

 

 

posted @ 2012-02-27 00:05  技术草根女  Views(536)  Comments(0Edit  收藏  举报