apache.commons.httpclient.HttpClient get/post请求

一、httpclient 发送请求的步骤(流程)

1、创建httpclient 对象

2、创建某种连接方式的对象 --如 GetMethod    PostMethod  等对象,构造函数中是请求地址即url,如果是get请求可以在url后面添加请求参数

如: http://127.0.0.1:8080/music?id=1&name=name

3、 调用第一步中创建好的实例的 execute 方法来执行第二步中创建好的 method 实例,也就是这时候发送了请求

4、获取服务器响应的值

5、关闭连接,这个和 连接数据库之后释放资源一样,执行之后要释放连接资源

6、处理获得的数据

 

二、核心代码:org.apache.commons.httpclient.HttpClient   get请求来实现,响应返回的数据格式为jsonobject格式

1、发送请求,请求成功响应数据的处理

    // 创建 httpclient 对象
    HttpClient  httpclient= new HttpClient();

   //创建请求方式
    GetMethod getMethod = new GetMethod("http://localhost:8080/music/user/delete.do?id=1");

    // 响应状态的判断

  try{
    int status= httpclient.executeMethod(getMethod);

   // 200  ok 请求成功,否则请求失败
    if(status!=HttpStatus.SC_OK){
        System.err.println("Method failed: "
                  + getMethod.getStatusLine());
        
    }

  // 请求成功,使用string获取响应数据

   String info = null;
    info = new String(getMethod.getResponseBodyAsString());

   // 请求成功,使用 byte数组来获取响应数据

    byte[] responsebody= getMethod.getResponseBody();

     // 编码要和 服务端响应的一致
    String response = new String(responsebody, "UTF-8");

    // 响应数据格式转化获取jsonobject

     JSONObject  json = new JSONObject();
      json=json.fromObject(response);
      String ids=json.getString("id");
      String names=json.getString("name");

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

    }catch(IOException ee){
        ee.printStackTrace();
    }finally{
        // 释放连接
        getMethod.releaseConnection();
    }

 

2、接收请求,处理请求以及请求的响应

// 完整的请求路径为:http://localhost:8080/music/user/delete.do    这里使用了springmvc 框架

@RequestMapping(value="/delete.do")

//  这里的id就是请求url后面的那个请求参数,可以有多个请求参数
public void  delete(Integer id,HttpServletResponse response){
    System.out.println("请求到达 delete");
    Integer yid= id;
    System.out.println("请求参数"+yid);
    try {

           // 获取输出流
        OutputStream output= response.getOutputStream();

          // 设置编码不然会出现乱码
        response.setCharacterEncoding("UTF-8");
   
        // 这里传递一个json 格式数据,
        JSONObject  json= new JSONObject();
        json.put("id", 10);
        json.put("name", "name");
        String jstring= json.toString();

         // 设置编码
        byte [] b= jstring.getBytes("UTF-8");

        // 响应,将相应数据返回 client
        output.write(b);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

服务器响应数据格式为 JSONArray

1、请求代码:

// 创建 httpclient 对象
    HttpClient  httpclient= new HttpClient();

   //创建请求方式
    GetMethod getMethod = new GetMethod("http://localhost:8080/music/user/delete.do?id=1");

    // 响应状态的判断

  try{
    int status= httpclient.executeMethod(getMethod);

   // 200  ok 请求成功,否则请求失败
    if(status!=HttpStatus.SC_OK){
        System.err.println("Method failed: "
                  + getMethod.getStatusLine());
        
    }

  // 请求成功,使用string获取响应数据

   String info = null;
    info = new String(getMethod.getResponseBodyAsString());

   // 请求成功,使用 byte数组来获取响应数据

    byte[] responsebody= getMethod.getResponseBody();

     // 编码要和 服务端响应的一致,而这里的response就是jsonarray 格式的字符串
    String response = new String(responsebody, "UTF-8");

    // 响应数据格式转化获取JSONArray

     JSONArray array= new JSONArray();
      array=array.fromObject(response);
   // 获取JSONArray 数组中的JSONObject

   JSONObject json= new JSONObject();
    JSONObject json1= new JSONObject();

 

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

    }catch(IOException ee){
        ee.printStackTrace();
    }finally{
        // 释放连接
        getMethod.releaseConnection();
    }

 

2、服务器端请求处理,响应代码

// 完整的请求路径url=http://localhost:8080/music/user/delete.do

@RequestMapping(value="/delete.do")
public void  delete(Integer id,HttpServletResponse response){
    System.out.println("请求到达 delete");

 // 请求参数
    Integer yid= id;
    System.out.println("请求参数"+yid);
    try {

           // 获取输出流
        OutputStream output= response.getOutputStream();

          // 编码设置
        response.setCharacterEncoding("UTF-8");
        // 这里传递一个json 格式数据
        JSONObject  json= new JSONObject();
        json.put("id", 10);
        json.put("name", "name");
        JSONObject  json1= new JSONObject();
        json1.put("id", 11);
        json1.put("name", "name1");

        // 将jsonobject 放进jsonobject
        JSONArray arr= new JSONArray();
        arr.add(json);
        arr.add(json1);
        String jstring= arr.toString();

         // 设置编码,如果编码方式不同会出现乱码
        byte [] b= jstring.getBytes("UTF-8");  

         //  请求响应,

         output.write(b);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

 

org.apache.commons.httpclient.HttpClient   post请求来实现,响应返回的数据格式为jsonobject格式

get请求和post请求之后参数的传递不同,其他的流程以及处理方式都是一样的,所以我们这里只写 多个请求参数返回JSONObject 的代码

1、请求代码:

// 创建 httpclient 对象
    HttpClient  httpclient= new HttpClient();
    //创建请求方式
    PostMethod postMethod = new PostMethod("http://localhost:8080/music/user/delete.do");
    //参数的设置,get的请求参数在url后面但是post的请求参数在请求主体中,因此这样写
    NameValuePair[] data = { new NameValuePair("id","110"),  new NameValuePair("name", "yourName") };
    // 将请求参数设置到  请求方法中

    postMethod.setRequestBody(data);

    // 设置请求编码方式,其中的 charset 就设置了编码方式。

    postMethod.addRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=gb2312");

     // http client 执行这个post请求方法
    try{

     // 服务器端返回的状态信息
    int status= httpclient.executeMethod(postMethod);
    if(status!=HttpStatus.SC_OK){
        System.err.println("Method failed: "
                  + postMethod.getStatusLine());
    }
    String info = null;

      // 获取响应信息
    info = new String(postMethod.getResponseBodyAsString());
    System.out.println("使用commons 的get方法请求获取的值"+info);
    // 获取响应信息

    byte[] responsebody= postMethod.getResponseBody();

     // 设置编码
    String response = new String(responsebody, "UTF-8");
    // 如果服务器段返回的是jsonobject格式则可以按照这种方式
    JSONObject  json = new JSONObject();
    json=json.fromObject(response);
    String ids=json.getString("id");
    String names=json.getString("name");
    System.out.println("id:"+ids +"  name:"+names );
    System.out.println("获取内容"+responsebody.toString()+"string 类型"+response);
    }catch(HTTPException e){
        e.printStackTrace();
    }catch(IOException ee){
        ee.printStackTrace();
    }finally{
        // 释放连接
        postMethod.releaseConnection();
    }
    return "index";
}
 

2、服务器端请求处理,响应代码

@RequestMapping(value="/delete.do")

//  接受post请求参数 id  name
public void  delete(String id,String name,HttpServletResponse response){
    System.out.println("请求到达 delete");
    String yid= id;
    String yname=name;
    System.out.println("请求参数"+yid);
    System.out.println("请求参数name:"+name);
    try {
        OutputStream output= response.getOutputStream();

          // 编码设置
        response.setCharacterEncoding("UTF-8");
        // 这里传递一个json 格式数据
        JSONObject  json= new JSONObject();
        json.put("id", 10);
        json.put("name", "name");
        String jstring= json.toString();

        // 编码设置
        byte [] b= jstring.getBytes("UTF-8");

         // 信息输出
        output.write(b);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

 

转载于:https://my.oschina.net/u/1454838/blog/400733

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值