HTTPConnection与HTTPClient

HTTPConnection

用HttpConnection连接服务器有两种方法:GET和POSIT

GET

代码如下:

String urlstring = "http://localhost:8080/MyserverTest/Test?name=zhaoliu&password=12";
                try {
                    URL url = new URL(urlstring);
                    URLConnection connect = url.openConnection();
                    HttpURLConnection httpconnection =(HttpURLConnection)connect;
                    //设置接收服务器的类型为GET
                    httpconnection.setConnectTimeout(30000);
                    httpconnection.setReadTimeout(30000);
                    httpconnection.setRequestMethod("GET");//用GET方法去接收服务器发来的数据。 
                    //设置接收的数据类型
                    httpconnection.setRequestProperty("Accept-Charset", "utf-8");
                    // 设置可以接受序列化的java对象
                    httpconnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    //获得http状态码若为200说明接通正常
                    int code =httpconnection.getResponseCode();
                    if(code==HttpsURLConnection.HTTP_OK){
                        //建立接受数据流
                        BufferedReader br=new BufferedReader(new InputStreamReader(httpconnection.getInputStream()));

                        String line =br.readLine();
                        while(line!=null){
                            System.out.println(line);
                            line =br.readLine();
                        }
                    }

                } catch(SocketTimeoutException e){
                    System.out.println("获取数据超时");

                } catch(ConnectException e){
                    System.out.println("网络连接超时");

                }catch(MalformedURLException e) {

                    e.printStackTrace();
                } catch (IOException e) {

                    e.printStackTrace();
                }
            }

说明:
在Httpconnection中无论是GET方法还是POST方法都是先得到URL对象url,通过URLConnection connect = url.openConnection();将连接打开。用httpconnection.setRequestMethod(“GET”);确定接收数据的方法。用httpconnection.setRequestProperty(“Accept-Charset”, “utf-8”);设置接收的数据类型。用httpconnection.setRequestProperty(“Content-Type”, “application/x-www-form-urlencoded”);设置可以接受序列化的java对象。用int code =httpconnection.getResponseCode();获得http状态码若为200说明接通正常。用httpconnection.getInputStream()获得输入流。这样就可以对数据进行读取了。
由于post传输的地址不能将传输的内容放到网址的后面(是隐式的)所以必须有输出流。所以必须对输出流进行允许即:httpconnection.setDoOutput(true);。由于post不允许用缓冲,所以用:httpconnection.setUseCaches(false);。其他的与GET基本相同。
代码如下:

URL url = new URL(urlstring);
                    URLConnection connect = url.openConnection();
                    HttpURLConnection httpconnection =(HttpURLConnection)connect;
                    //设置接收服务器的类型为GET
                    httpconnection.setConnectTimeout(30000);
                    httpconnection.setReadTimeout(30000);
                    httpconnection.setRequestMethod("POST");                                        
                    //设置接收的数据类型
                    httpconnection.setRequestProperty("Accept-Charset", "utf-8");
                    // 设置可以接受序列化的java对象
                    httpconnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    //获得http状态码若为200说明接通正常
                    httpconnection.setDoOutput(true);//设置向服务器发送数据是允许的,在post方法中这是必须为true
                    httpconnection.setDoInput(true);//设置可读取服务器的返回值,默认为true,可以不用设置
                    httpconnection.setUseCaches(false);//post方法不允许使用缓存
                    String s = "name=zhansan&password=123";
                    httpconnection.getOutputStream().write(s.getBytes());//设置输出流
                    int code =httpconnection.getResponseCode();//获得http状态码
                    if(code==HttpsURLConnection.HTTP_OK){//如果连接成功
                        //建立接受数据流
                        BufferedReader br=new BufferedReader(new InputStreamReader(httpconnection.getInputStream()));

                        String line =br.readLine();
                        while(line!=null){
                            System.out.println(line);
                            line =br.readLine();
                        }
                    }

                } catch(SocketTimeoutException e){
                    System.out.println("获取数据超时");

                } catch(ConnectException e){
                    System.out.println("网络连接超时");

                }catch(MalformedURLException e) {

                    e.printStackTrace();
                } catch (IOException e) {

                    e.printStackTrace();
                }

HttpClient

ThhpClient也是分两种GET和POST

GET

代码如下:

String URLString = "http://localhost:8080/MyserverTest/Test?name=zhaoliu&password=12";
                HttpClientBuilder builder = HttpClientBuilder.create();
                builder.setConnectionTimeToLive(3000, TimeUnit.MICROSECONDS);//设置连接时间
                HttpClient client = builder.build();//生成client
                HttpGet get=new HttpGet(URLString);//设置为get方法
                get.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
                //设置服务器接收后数据的读取方式为utf8
                try {
                    HttpResponse response=client.execute(get);//执行get方法得到服务器的返回的所有数据都在response中
                    StatusLine statusLine=response.getStatusLine();//httpClient访问服务器返回的表头,包含http状态码
                    int code=statusLine.getStatusCode();//得到状态码
                    if(code==HttpURLConnection.HTTP_OK){
                        HttpEntity entity=response.getEntity();//得到数据的实体
                        InputStream is=entity.getContent();//得到输入流
                        BufferedReader br=new BufferedReader(new InputStreamReader(is));
                        String line=br.readLine();
                        while(line!=null){
                            System.out.println(line);
                            line=br.readLine();
                        }
                    }
                } catch (ClientProtocolException e1) {

                    e1.printStackTrace();
                } catch (IOException e1) {

                    e1.printStackTrace();
                }

GET与POST的的方法差不多和HttpConnection一样GET是显式,POST是隐式:(1)获得builder:HttpClientBuilder builder = HttpClientBuilder.create();(2)获得client :HttpClient client = builder.build();//生成client。(3)获得GET方法或者POST方法。
GET代码如下:

String URLString = "http://localhost:8080/MyserverTest/Test?name=zhaoliu&password=12";
                HttpClientBuilder builder = HttpClientBuilder.create();
                builder.setConnectionTimeToLive(3000, TimeUnit.MICROSECONDS);//设置连接时间
                HttpClient client = builder.build();//生成client
                HttpGet get=new HttpGet(URLString);//设置为get方法
                get.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
                //设置服务器接收后数据的读取方式为utf8
                try {
                    HttpResponse response=client.execute(get);//执行get方法得到服务器的返回的所有数据都在response中
                    StatusLine statusLine=response.getStatusLine();//httpClient访问服务器返回的表头,包含http状态码
                    int code=statusLine.getStatusCode();//得到状态码
                    if(code==HttpURLConnection.HTTP_OK){
                        HttpEntity entity=response.getEntity();//得到数据的实体
                        InputStream is=entity.getContent();//得到输入流
                        BufferedReader br=new BufferedReader(new InputStreamReader(is));
                        String line=br.readLine();
                        while(line!=null){
                            System.out.println(line);
                            line=br.readLine();
                        }
                    }
                } catch (ClientProtocolException e1) {

                    e1.printStackTrace();
                } catch (IOException e1) {

                    e1.printStackTrace();
                }
            }

POST代码如下:

String url = "http://localhost:8080/MyserverTest/Test";
                HttpClientBuilder builder = HttpClientBuilder.create();
                HttpClient client =builder.build();
                HttpPost post1 =new HttpPost(url);
                NameValuePair pair1 =new BasicNameValuePair("name", "zhaoliu");
                NameValuePair pair2 =new BasicNameValuePair("password", "12");  
                ArrayList<NameValuePair> array = new ArrayList<>();
                array.add(pair1);
                array.add(pair2);
                try {
                    post1.setEntity(new UrlEncodedFormEntity(array, "UTF-8"));
                    post1.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
                    HttpResponse request = client.execute(post1);
                    int code= request.getStatusLine().getStatusCode();
                    if(code==200){
                        HttpEntity entity=request.getEntity();
                        InputStream is =entity.getContent();
                        BufferedReader br =new BufferedReader(new InputStreamReader(is));
                        String line =br.readLine();
                        while(line!=null){
                            System.out.println(line);
                            line =br.readLine();
                        }

                    }
                } catch (UnsupportedEncodingException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }

这里有许多的地方不是很懂,以后用到再仔细看。
一篇不 错的文章:
http://www.cnblogs.com/devinzhang/archive/2012/02/06/2340186.html

你可能感兴趣的:(HTTPConnection与HTTPClient)