前后端分离-httpclient

package com.hjs.controller;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hjs.entity.User;

import net.sf.json.JSONObject;

@RequestMapping("httpClient")
@Controller
public class HttpTest {
    @RequestMapping("/postAction")
    @ResponseBody
    public String httpPostMap(User user) {
        //创建httpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        String url="http://localhost:8080/user/addUser";
        try {
            HttpPost post=new HttpPost(url);
            Map<String, Object> map=new HashMap<>();
            map=objectToMap(user);
            if(map!=null) {
                 List<NameValuePair> paramList = new ArrayList<>();
                    for (String key : map.keySet()) {
                        paramList.add(new BasicNameValuePair(key, map.get(key).toString()));
                    }
                  // 模拟表单
                  UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList, "UTF-8");
                  post.setEntity(entity);
            }
             // 执行http请求
            post.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
            response = httpClient.execute(post);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
        }catch(Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭连接,释放资源  
            try {
                httpClient.close();
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultString;
    }
    /**
     * String url,String json 可以作为参数
     * @return
     */
    @RequestMapping("/postAndJson")
    public String postAndJson(User user) {
        //创建httpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String resultString = "";
        new JSONObject();
        String  json=JSONObject.fromObject(user).toString();
        System.out.println("数据格式:"+json);
        String url="http://localhost:8080/user/addUser";
        try {
            // 创建Http Post请求
            HttpPost httpPost = new HttpPost(url);
            // 创建请求内容
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
            httpPost.setEntity(entity);
            // 执行http请求
            response = httpClient.execute(httpPost);
            resultString = EntityUtils.toString(response.getEntity(), "utf-8");
            System.out.println(response.getStatusLine()+"--------"+resultString);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        return resultString;
    }
    @RequestMapping("/paramPost")
    public String paramPost(User user) {
        //创建httpClient对象
            CloseableHttpClient httpClient = HttpClients.createDefault();
            CloseableHttpResponse response = null;
            String resultString = "";
            String url="http://localhost:8080/user/addUser";
            try {
                // 创建Http Post请求
                HttpPost post = new HttpPost(url);
                List<BasicNameValuePair> formparams = new ArrayList();
                formparams.add(new BasicNameValuePair("name", user.getName()));
                formparams.add(new BasicNameValuePair("age", user.getAge().toString()));
                UrlEncodedFormEntity uefEntity;
                uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
                post.setEntity(uefEntity);
                System.out.println("executing request " + post.getURI());
                System.out.println(post.getEntity());
                response=httpClient.execute(post);
                try {
                    HttpEntity entity = (HttpEntity) response.getEntity();
                    if (entity != null) {
                        System.out.println("--------------------------------------");
                        System.out.println("Response content: " + EntityUtils.toString(entity, "UTF-8"));
                        System.out.println("--------------------------------------");
                    }
                } finally {
                    response.close();
                }
                System.out.println(response.getStatusLine());
            }catch(Exception e) {
                e.printStackTrace();
            } finally {
                // 关闭连接,释放资源  
                try {
                    httpClient.close();
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return resultString;
    }
    
    public static Map<String, Object> objectToMap(Object obj) throws IllegalAccessException {
        Map<String, Object> map = new HashMap<String,Object>();
        Class<?> clazz = obj.getClass();
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true);
            String fieldName = field.getName();
            //Object value = StringUtils.nvl(field.get(obj));
            map.put(fieldName, field.get(obj));
        }
        return map;
    }
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值