HttpClient的使用指南

来源:互联网 发布:java中构造方法的使用 编辑:程序博客网 时间:2024/06/15 15:31

使用HttpClient可以在客户端发送Post请求,请求访问服务端的Servlet, 依赖包httpclient和httpcore,http://hc.apache.org/httpcomponents-client-4.4.x/index.html上下载,这里所用的是httpcomponents-client-4.4.1-bin.tar.gz.

public void sendPostMethod(){      DefaultHttpClient httpclient = new DefaultHttpClient();      //参数代表目标地址      HttpPost httppost = new HttpPost("http://172.18.60.2:8080/MyFirstWeb/TestServlet");            // HttpPost参数传递      List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();      nvps.add(new BasicNameValuePair("user", "chris"));      nvps.add(new BasicNameValuePair("name", "benpaoba"));     nvps.add(new BasicNameValuePair("age", "25"));       try {        httppost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));        // 执行请求HttpResponse response = httpclient.execute(httppost);  HttpEntity entity = response.getEntity();  if (entity != null) {       System.out.println("Response content length: "              + entity.getContentLength());  }  // 显示结果  BufferedReader reader = new BufferedReader(new InputStreamReader(          entity.getContent(), "UTF-8"));  String line = null;  while ((line = reader.readLine()) != null) {          System.out.println(line);  }  if (entity != null) {      entity.consumeContent();  }      } catch (UnsupportedEncodingException e) {        // TODO Auto-generated catch blocke.printStackTrace();    } catch (UnsupportedOperationException e) {        // TODO Auto-generated catch block        e.printStackTrace();    } catch (IOException e) {        // TODO Auto-generated catch block        e.printStackTrace();    } finally {        httpclient.getConnectionManager().shutdown();    }}

0 0
原创粉丝点击