SpringMVC template和HttpClient post提交

服务器的接口如果是springmvc,客户端除了用springmvc提供的RestTemplate请求,如下:

public class RestClient {

    private static Logger logger = Logger.getLogger(RestClient.class);

    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static Object post(String url, Map<String, Object> message) {
        Object result = null;
        try {
            RestTemplate rest = new RestTemplate();
            MultiValueMap<String, Object> param = new LinkedMultiValueMap();
            for(Entry<String, Object> entry : message.entrySet()) {
                param.add(entry.getKey(), entry.getValue());
            }
            result = rest.postForObject(url, param, String.class);
        } catch (Exception e) {
            logger.error("发送消息发生异常"+e);
        }
        return result;
    }
}

还可以用httpclient发送请求,如下:

package com.ckdh.web.test;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;

public class DownloadResourcesTest {

    public static void main(String[] args) {
        String url = "http://localhost:8080/xxx-web/xxx.mvc?apikey=1";
        HttpClient client = new DefaultHttpClient();  
        HttpPost httpPost = new HttpPost(url); 
        InputStream is = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        try {
            httpPost.addHeader("city", "010");
            httpPost.addHeader("version", "2");
            HttpEntity entity = new StringEntity("<infos><info spid=\"188\" hash=\"4a0fd9704eb1432892cbc19742811b63\">" +
                    "</info><info spid=\"1601\" hash=\"4e7b8894b8bc4d4eac22dffd85f28a68\"></info></infos>");
            httpPost.setEntity(entity);
            HttpResponse response = client.execute(httpPost);
            System.out.println(response.getStatusLine());
            is = response.getEntity().getContent();
            isr = new InputStreamReader(is, "UTF-8");
            br = new BufferedReader(isr);
            StringBuffer buf = new StringBuffer();
            String line;
            while (null != (line = br.readLine())) {
                buf.append(line).append("\n");
            }
            System.out.println(buf.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值