HttpClient Get和Post

Get的使用
第一步:创建一个HttpClientBuilder,它的作用是:用来创建Client,现在已 经淘汰,DefaultHttpClient的创建使用 了。
第二部:利用HttpClientBuilder 创建的对象来创建一个 HttpClient。(可以利用以上创建的两对象设置参数)
第三步:用httpGet创建一个对象,用来连接服务器。
第四部:得到服务器返回的数据,HttpResponse 用来得到数据StatusLine是得到的表头数据,HttpEntity还http表征实体,HttpEntity.getContent()是得到内容。最后用流进行解析。
具体列子:

//建一个url
                String url="http://localhost:8080/TestWeb/TestServerlet?username=张三&password=123";
                //创建一个buider
                HttpClientBuilder builder=HttpClientBuilder.create();
                builder.setConnectionTimeToLive(30000, TimeUnit.MILLISECONDS);//这是链接超时
                HttpClient client=builder.build();//利用builder来创建一个client
                HttpGet get=new HttpGet(url);//创建一个HttpGet用来链接服务器
                try {
                    HttpResponse response=client.execute(get);//创建一个response来接收服务器的数据
                    StatusLine statusline=response.getStatusLine();//得到表头,表头是来存放这个服务器返回数据的标示
                    int code=statusline.getStatusCode();//得到链接状态
                    if(code==HttpURLConnection.HTTP_OK){
                        HttpEntity entity=response.getEntity();//收到的一个HTTP表征实体
                        InputStream is=entity.getContent();//得到里面的内容
                        BufferedReader bread=new BufferedReader(new InputStreamReader(is));
                        String line=bread.readLine();
                        while(line!=null){
                            System.out.println(line);
                            line=bread.readLine();
                        }
                    }
                } catch (ClientProtocolException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

post的使用
post的使用,比get多了数据封装。不再是通过url进行数据传输,post用arryList对数据进行封装(利用ArrayList的高访问性),在用Entity将数据封装成http表征实体,进行传输,其中注意两次的编码设置,一次将arraylist设置成utf-8,一次是entity包传输数据类型为java数据类型,(”content-type”,”application/x-www-form-urlencoded;charset=utf-8”);(而服务的返回类型是content-type,text/html;charset=utf-8);
实例

String url = "http://localhost:8080/CLient_Server/CheckLogin";
        HttpClientBuilder builder = HttpClientBuilder.create();
        HttpClient client = builder.build();
        builder.setConnectionTimeToLive(10000, TimeUnit.MILLISECONDS);
        HttpPost post = new HttpPost(url);
        JSONObject obj = new JSONObject();
        JSONObject json = new JSONObject();
        obj.put("type", "login");
        json.put("username", username);
        json.put("password", password);
        obj.put("data", json);
        NameValuePair pair = new BasicNameValuePair("json", obj.toString());
        ArrayList<NameValuePair> array = new ArrayList<>();
        array.add(pair);
        try {
            UrlEncodedFormEntity urlencode = new UrlEncodedFormEntity(array, "utf-8");
            post.setEntity(urlencode);
            post.setHeader("content-type", "application/x-www-form-urlencoded;charset=utf-8");
            HttpResponse reponse = client.execute(post);
            StatusLine statusline = reponse.getStatusLine();
            int code = statusline.getStatusCode();
            if (code == HttpURLConnection.HTTP_OK) {
                HttpEntity entity = reponse.getEntity();
                InputStream is = entity.getContent();
                BufferedReader bread = new BufferedReader(new InputStreamReader(is));
                String line = bread.readLine();
                System.out.println(line);
                messageLogin = line;
            }
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return messageLogin;
    }

    public String register(String username, String password) {
        String messageRegister = "";
        String url = "http://localhost:8080/CLient_Server/CheckLogin";
        HttpClientBuilder builder = HttpClientBuilder.create();
        HttpClient client = builder.build();
        builder.setConnectionTimeToLive(10000, TimeUnit.MILLISECONDS);
        JSONObject json = new JSONObject();
        JSONObject data = new JSONObject();
        data.put("username", username);
        data.put("password", password);
        json.put("type", "register");
        json.put("data", data);
        HttpPost post = new HttpPost(url);
        NameValuePair pair = new BasicNameValuePair("json", json.toString());
        ArrayList<NameValuePair> array = new ArrayList<>();
        array.add(pair);
        try {
            UrlEncodedFormEntity urlEncoded = new UrlEncodedFormEntity(array, "utf-8");
            post.setEntity(urlEncoded);
            post.setHeader("content-type", "application/x-www-form-urlencoded;charset=utf-8");
            HttpResponse response = client.execute(post);
            StatusLine statusline = response.getStatusLine();
            int code = statusline.getStatusCode();
            if (code == HttpURLConnection.HTTP_OK) {
                HttpEntity entity = response.getEntity();
                InputStream is = entity.getContent();
                BufferedReader bread = new BufferedReader(new InputStreamReader(is));
                String line = bread.readLine();
                messageRegister = OperationJson.analyzeJson(line);
            }
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值