服务器的接口如果是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;
}
}
import java.io.UnsupportedEncodingException;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import test.ThreeDES;
public class TestPost {
public static void main(String[] args) {
//spring方式
RestTemplate rest = new RestTemplate();//创建org.springframework.web.client.RestTemplate
MultiValueMap<String,Object> param = new LinkedMultiValueMap<String,Object>();//创建参数Map org.springframework.util.LinkedMultiValueMap
//map设值
param.add("id", "1");
param.add("carbonOrderNo", "M201702161055");
param.add("name", "王烟");
param.add("userTypes", "OTHER");
param.add("tel", "13020232323");
param.add("certificateNo", "99021023456");
param.add("money", "2");
param.add("donationWays", "CASHPAY");
String result = rest.postForObject("http://localhost:8080/trip/bD/send?", param, String.class);//postForObject post方式
System.out.println(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 hash="a0fd9704eb1432892cbc19742811b63" spid="88"> +
</info><info hash="e7b8894b8bc4d4eac22dffd85f28a68" spid="p1"></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();
}
System.out.println(buf.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}