Spring mvc REST风格对外接口,HttpClient调用
来源:互联网 发布:炉石淘宝买卡背 编辑:程序博客网 时间:2024/05/18 17:01
客户端代码
所需jar
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(); }}
- 服务端(此处使用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" />
- 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>
8 0
- Spring mvc REST风格对外接口,HttpClient调用
- spring mvc rest 优雅风格
- spring mvc的 rest风格
- Spring mvc rest 风格实例
- 关于HttpClient(调用openstack rest接口失败)
- spring MVC 配置rest风格URL
- Spring MVC搭建REST风格网站
- spring mvc和rest风格小例子
- Spring MVC--7.REST风格 CRUD
- spring mvc rest风格的CRUD
- REST风格编写Spring MVC的CRUD
- spring boot(3)-Rest风格接口
- spring boot(3)-Rest风格接口
- spring rest mvc使用RestTemplate调用
- spring rest mvc使用RestTemplate调用
- 使用Spring MVC构建REST风格WEB应用
- 5分钟构建spring web mvc REST风格HelloWorld
- 5分钟构建spring web mvc REST风格HelloWorld
- jq中append()、prepend()、after()、before()的区别详解
- 分割线
- Thread.yield( )
- JavaIO之文件目录操作
- 使用lcov生成代码覆盖率的报告
- Spring mvc REST风格对外接口,HttpClient调用
- SpringBoot 学习记录(六): Exception
- python3.6 Tkinter 入门
- windows 下单机部署rabbitmq 集群
- 神经网络视觉循迹小车
- C++中指针,引用,const,static总结
- Leetcode --9
- opencv Mat创建图像
- Fiddler与Charles的特殊用途 一、Fiddle2(v2.4.2.6,windows) fiddler除了常规的替换http请求、模拟慢网速外,还有一些日常开发里能用到的特