SpringMVC template和HttpClient post提交

来源:互联网 发布:淘宝助理5.8.7.0 编辑:程序博客网 时间:2024/06/10 10:49

服务器的接口如果是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();        }    }}
0 0
原创粉丝点击