httpclient应用

httpclient应用:

 

准备需要的jar包

* commons-httpclient-3.0.jar
* commons-logging.jar
* commons-codec-1.3.jar

 

class&method

HttpClient

GetMethod

PostMethod

 

项目中调用后台jetty上的接口,用的get方式;现将代码放上;

例子:

public static String callServer(String url) {

        String resultString = null;
        HttpClient client = new HttpClient();
        GetMethod method = new GetMethod(url);
        try {
            int status = client.executeMethod(method);
            if (status == HttpStatus.SC_OK) {
                resultString = method.getResponseBodyAsString();
            }
        } catch (HttpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            method.releaseConnection();
        }
        return resultString;
    }

 

post方式也类似,只是参数传递有点差别;

举例如下:

  public static String postHttp(String param1,String param2) {
         String responseMsg = "";
         
        //1.构造HttpClient的实例
          HttpClient httpClient=new HttpClient();       
          httpClient.getParams().setContentCharset("GBK");
        
        String url="url";
        
   //2.构造PostMethod的实例
         PostMethod postMethod=new PostMethod(url);   
        //3.把参数值放入到PostMethod对象中
  //方式1:
 /*        NameValuePair[] data = { new NameValuePair("param1", param1),
                 new NameValuePair("param2", param2) };
          postMethod.setRequestBody(data);*/
         
         //方式2:   
        postMethod.addParameter("param1", param1);
        postMethod.addParameter("param2", param2);
      
       
        try {
             // 4.执行postMethod,调用http接口
            httpClient.executeMethod(postMethod);//200
            
 //5.读取内容
               responseMsg = postMethod.getResponseBodyAsString().trim();
             //6.处理返回的内容

         } catch (HttpException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
//7.释放连接

       postMethod.releaseConnection();
        }
         return responseMsg;
     }

 

 

 

通过get和post方式调用http接口,总结如下:

* get方式调用http接口的步骤:
* 1.构造HttpClient实例
* 2.构造GetMethod实例
* 3.执行getMethod,调用http接口
* 4.读取内容
* 5.处理返回的内容
* 6.释放连接
*
* post方式调用http接口的步骤
* 1.构造HttpClient实例
* 2.构造PostMethod实例
* 3.把参数值放入到PostMethod对象中
*   方式1:利用NameValuePair类
*   方式2:直接用PostMethod实例对象的addParameter方法
* 4.执行postMethod,调用http接口
* 5.读取内容
* 6.处理返回的内容
* 7.释放连接

你可能感兴趣的:(httpclient)