HTTPConnection与HTTPClient
2015-08-12 19:44
417 查看
HTTPConnection
用HttpConnection连接服务器有两种方法:GET和POSITGET
代码如下: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和POSTGET
代码如下: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(); } }
这里有许多的地方不是很懂,以后用到再仔细看。
一篇不 错的文章:
/article/4783929.html
相关文章推荐
- http://blog.sina.com.cn/s/blog_777a9ccb01013maj.html
- Java判断和检查网络
- TCP/IP网络编程 学习笔记_9 --域名系统(DNS)
- TCP/IP网络编程 学习笔记_9 --域名系统(DNS)
- 黑马程序员——java学习14(毕23-24)——网络编程
- http服务器交互get,put,post,delete等概念
- 网络篇----数据安全
- iOS安全系列之一:HTTPS
- Android网络取数据显示到ListView实例
- 卷积神经网络(CNN)笔记
- TCP/IP、Http、Socket的区别
- Http 异步批量下载图片之优化
- IOS--http状态码快速查看
- iOS安全系列之 HTTPS
- android中Http和HttpClient的Get和Post方法的使用
- http异步大量图片下载,并用GridView显示九宫格图片样式
- 通过http user-agent判断是否为手机浏览器
- 运行中修改协调器PAN ID和Channel,协调器广播至所有的设备重启加入新建后的网络
- MFC快速实现网络编程CAsyncSocket类
- 计算机网络之面试常考