通常用json進(jìn)行web端的數(shù)據(jù)發(fā)送盐股,但是大部分都是簡單的string類型的鍵值對(duì),可以直接用NameValuePair這個(gè)就谜,快速的搭建舷胜,從而進(jìn)行http的對(duì)接娩践。
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
public class test {
public static void main(String[] args) throws ClientProtocolException, IOException {
// TODO Auto-generated method stub
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost("http://ip:port/api-test");
List<NameValuePair> pairs = new ArrayList<NameValuePair>();
pairs.add(new BasicNameValuePair("deviceid", "df465-df5-df4533-sdf"));
pairs.add(new BasicNameValuePair("companyId", "bettershine"));
pairs.add(new BasicNameValuePair("managerName", "張三"));
pairs.add(new BasicNameValuePair("managerPhone", "123456789"));
httpPost.setEntity(new UrlEncodedFormEntity(pairs, "utf-8"));
CloseableHttpResponse response = httpClient.execute(httpPost);
String result = EntityUtils.toString(response.getEntity(), "utf-8");
System.out.println("返回結(jié)果:"+result);
}
}