Spring mvc REST风格对外接口,HttpClient调用

客户端代码

  1. 所需jar
    这里写图片描述

  2. HttpClient代码

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import com.itcast.httpClient.bean.User;



/**
 1. 测试HttpClient
 2. @author sWX300935
 3.  */
@SuppressWarnings("deprecation")
public class HttpClientTest {

    //get接口掉方法
    public static String callInterface(){
        HttpClient httpClient = new DefaultHttpClient();

        HttpGet httpGet = new HttpGet("http://localhost:8080/testSpringMVC/httpService/req/userInfo/zhangsan");

        String entityStr = null;
        try {
            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity entity = httpResponse.getEntity();
            StatusLine statusLine = httpResponse.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            System.out.println("statusCode:"+statusCode);
            entityStr = EntityUtils.toString(entity);
            System.out.println("响应返回内容:"+entityStr);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return entityStr;
    }

    //post提交调用方法
    public static String callAddUserInfo() throws UnsupportedEncodingException{
        User user = new User();
        user.setUserName("小文");
        user.setUserAge("15");
        user.setUserSex("女");

        String str = JSONObject.fromObject(user).toString();
        System.out.println(str);
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost("http://localhost:8080/testSpringMVC/httpService/req/addUserInfo");
        httpPost.setEntity(new StringEntity("str="+str, Charset.forName("utf-8")));

        //httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");  
          /* httppost.getParams().setParameter(HTTP.CONTENT_ENCODING, HTTP.UTF_8);  
           httppost.getParams().setParameter(HTTP.CHARSET_PARAM, HTTP.UTF_8);  
           httppost.getParams().setParameter(HTTP.DEFAULT_PROTOCOL_CHARSET, HTTP.UTF_8); */
        try {
            HttpResponse response = httpClient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            System.out.println(statusCode);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } 

        return null;
    }

    public static void main(String[] args) throws Exception {
        //String callInterface = callInterface();
        //System.out.println("调用成功:"+callInterface);
        callAddUserInfo();

    }
}
  1. 服务端(此处使用springMVC提供接口,springMVC不做描述)

javax.ws.rs-api-2.0.jar 需导入 用来创建RESTful服务资源 设置媒体资源

import javax.ws.rs.core.MediaType;

import net.sf.json.JSONObject;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.itcast.bean.User;
/**
 Http服务端
 */
@Controller
@RequestMapping(value = "/httpService")
public class HttpServiceDemo {
    /*GET方式*/
    @ResponseBody
    @RequestMapping(value = "/req/userInfo/{userName}",method = RequestMethod.GET,produces="application/json;charset=UTF-8")
    public String getUserInfo(@PathVariable("userName") String userName){
        if(userName.equals("zhangsan") ){
        User getUser = new User();
        getUser.setUserName("zhangsan");
        getUser.setUserAge("20");
        getUser.setUserSex("男");
        String userString = JSONObject.fromObject(getUser).toString();
        return userString;
        }
        return "{\"error\":\"请求数据为空\"}";
    }
    /*POST方式*/
    @ResponseBody
    @RequestMapping(value="/req/addUserInfo",method = RequestMethod.POST,
    produces = {MediaType.APPLICATION_JSON,"application/json;charset=UTF-8"})
    //consumes = {MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML})
    public String addUserInfo(@RequestBody String str){
        //@RequestBody User user
        System.out.println(str);
        return null;
    }

}

5.配置spring-mvc.xml

<!-- 设置注解驱动 -->
    <mvc:annotation-driven/>
    <!-- 配置只扫面controller的注解过滤器 -->
    <context:component-scan base-package="com.itcast" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

      <!-- 消息适配器 -->  
     <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">  
        <property name="messageConverters">  
            <list>  
                <ref bean="stringHttpMessageConverter" />  
                <ref bean="jsonHttpMessageConverter" />  
            </list>  
        </property>  
    </bean>  

    <bean id="stringHttpMessageConverter" class="org.springframework.http.converter.StringHttpMessageConverter">  
        <property name="supportedMediaTypes">  
            <list>  
                <value>text/plain;charset=UTF-8</value>  
                <value>application/json;charset=UTF-8</value>  
            </list>  
        </property>  
    </bean>   

    <bean id="jsonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />  
  1. web.xml
<servlet>
        <servlet-name>springMVC</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:Spring-MVC.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springMVC</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
  • 11
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值