利用NameValuePair快速构建键值对进行http发送

通常用json进行web端的数据发送,但是大部分都是简单的string类型的键值对,可以直接用NameValuePair这个,快速的搭建,从而进行http的对接。

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 pairs =  new ArrayList();
    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("返回结果:"+result);
}

}

你可能感兴趣的:(利用NameValuePair快速构建键值对进行http发送)