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

客户端代码

  1. 所需jar
    Spring mvc REST风格对外接口,HttpClient调用_第1张图片

  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/>
    
    <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-8value>  
                <value>application/json;charset=UTF-8value>  
            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>

你可能感兴趣的:(mybatis)