spring一个项目调用另一个项目接口的方法,HttpClient调用 - Go语言中文社区

spring一个项目调用另一个项目接口的方法,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
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  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;
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43

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
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  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>
版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/qq_39478853/article/details/78443300
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-03-08 16:37:50
  • 阅读 ( 1791 )
  • 分类:

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢