如何在java中利用HttpClient对json格式的参数进行传输
创始人
2024-12-29 03:01:50
0次

重点是这两句话:

httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
se.setContentType(CONTENT_TYPE_TEXT_JSON);

这两句话的作用与jmeter的设置header信息类似

package com.base;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.util.EntityUtils;
/** 
 * @author QiaoJiafei 
 * @version 创建时间:2015年11月4日 下午1:55:45 
 * 类说明 
 */
public class HttpGetByJson {
 public static void main(String args[]) throws Exception{
  final String CONTENT_TYPE_TEXT_JSON = "text/json";
  DefaultHttpClient client = new DefaultHttpClient(
   new PoolingClientConnectionManager());
  
  String url = "http://172.16.30.226:8091/svc/authentication/register";
 String js = "{\"userName\":\"18600363833\",\"validateChar\":\"706923\",\"randomChar\":\"706923\",\"password\":\"123456\",\"confirmPwd\":\"123456\",\"recommendMobile\":\"\",\"idCard\":\"320601197608285792\",\"realName\":\"阙岩\",\"verifyCode\"}";
  
 HttpPost httpPost = new HttpPost(url); 
 httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
  
 StringEntity se = new StringEntity(js);
 se.setContentType(CONTENT_TYPE_TEXT_JSON);
 httpPost.setEntity(se);
 
 CloseableHttpResponse response2 = null;
 
 response2 = client.execute(httpPost);
 HttpEntity entity2 = null;
 entity2 = response2.getEntity();
 String s2 = EntityUtils.toString(entity2, "UTF-8");
 System.out.println(s2);
 }
 
}

补充:HttpClient以json形式的参数调用http接口并对返回的json数据进行处理(可以带文件)

1、参数的url就是被调用的地址,map是你要传的参数。参数转成json我使用的是gson方式转换的。

主要使用的jar包有httpclient-4.5.3.jar、httpcore-4.4.6.jar、commons-codec-1.9.jar、gson-2.2.4.jar和commons-logging-1.2.jar。

如果发送的post请求想传送文件,需添加httpmime-4.5.3.jar包,并设置如下代码:

HttpEntity multipartEntityBuilder = MultipartEntityBuilder.create().addBinaryBody("file", new File("D:\\workspace\\programm\\WebContent\\programm\\1991.zip")).build();

第一个参数表示请求字段名,第二个参数就是文件。

还想添加参数则

HttpEntity multipartEntityBuilder = MultipartEntityBuilder.create().addTextBody("name", "张三").addBinaryBody("file", new File("D:\\workspace\\programm\\WebContent\\programm\\1991.zip")).build();
httpPost.setEntity(multipartEntityBuilder);
import java.io.IOException;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import com.google.gson.Gson;
public class HttpClientUtil {
 
 private final static String CONTENT_TYPE_TEXT_JSON = "text/json";
 
 public static String postRequest(String url, Map param) throws ClientProtocolException, IOException{
 
 CloseableHttpClient client = HttpClients.createDefault();
 HttpPost httpPost = new HttpPost(url);
 httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
 
 Gson gson = new Gson();
 String parameter = gson.toJson(param);
 StringEntity se = new StringEntity(parameter);
 se.setContentType(CONTENT_TYPE_TEXT_JSON);
 httpPost.setEntity(se);
 CloseableHttpResponse response = client.execute(httpPost);
 HttpEntity entity = response.getEntity();
 String result = EntityUtils.toString(entity, "UTF-8");
 
 return result;
 }
}

2、返回的结果也可以使用gson转换成对象进行下一步操作。

import com.google.gson.Gson;
public class GsonUtil {
 public static  T jsonToObject(String jsonData, Class type) {
 Gson gson = new Gson();
 T result = gson.fromJson(jsonData, type);
 return result;
 }
 
 public static void main(String[] args) {
 String json = "{'id':'1','name':'zhang','address':'Hubei'}";
 jsonToObject(json, Person.class);
 Person person = jsonToObject(json, Person.class);
 System.out.println(person);
 }
}

建立要转成的对象的类。

import java.util.Date;
public class Person {
 
 private int id;
 
 private String name;
 
 private int age;
 
 private String address;public int getId() {
 return id;
 }
 public void setId(int id) {
 this.id = id;
 }
 public String getName() {
 return name;
 }
 public void setName(String name) {
 this.name = name;
 }
 public int getAge() {
 return age;
 }
 public void setAge(int age) {
 this.age = age;
 }
 public String getAddress() {
 return address;
 }
 public void setAddress(String address) {
 this.address = address;
 }
 @Override
 public String toString() {
 return "Person [id=" + id + ", name=" + name + ", age=" + age + ", address=" + address + "]";
 }
}

3、发送以键值对形式的参数的post请求

package com.avatarmind.httpclient;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
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.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
public class HttpClient3 {
 
 public static void main(String[] args) throws Exception {
 CloseableHttpClient client = HttpClients.createDefault();
 String url = "http://yuntuapi.amap.com/datamanage/table/create";
 HttpPost httpPost = new HttpPost(url);
 // 参数形式为key=value&key=value
 List formparams = new ArrayList();
 formparams.add(new BasicNameValuePair("key", "060212638b94290e3dd0648c15753b64"));
 formparams.add(new BasicNameValuePair("name", "火狐"));
  
 // 加utf-8进行编码
 UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
 httpPost.setEntity(uefEntity);
 CloseableHttpResponse response = client.execute(httpPost);
 HttpEntity entity = response.getEntity();
 String result = EntityUtils.toString(entity, "UTF-8");
 System.out.println(result);
 }
}

相关内容

热门资讯

空调连续工作多久需要停机休息 空调连续工作的时间取决于多个因素,包括空调的型号、功率、使用环境和维护情况等。一般来说,空调可以连续...
空调哪个符号是除湿的 空调除湿功能通常用一个水滴形状的符号表示。不同品牌和型号的空调遥控器可能会有所差异,但一般来说,除湿...
格力空调多长时间加一次氟利昂 1、一般情况下,空调对氟利昂的使用量是非常小的,所以在空调使用了四年左右的时候再考虑加也没问题。2、...
空调用多长时间需要加氟一次 一般情况下是五年。当出现以下这几种情况时,空调才需要加氟。1、空调的室内机和室外机各有两个接口,当接...
格调生活·C标思享荟:卡萨帝在... 9月12日的郑州龙湖金融岛,夜风轻拂,灯光璀璨。“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑...
品牌价值破千亿、高端份额持续领... 9月12日,“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑州站”在郑州龙湖金融岛举办。2026...
空调主板坏了修800还是换新的 空调主板坏了是修还是换新,需要考虑多个因素,以下是一些建议:1. 维修成本:如果维修费用较低,比如 ...
空调开多久需要休息多长时间 问题:空调开多久需要休息多长时间回答:1、在使用空调的过程中,一般空调开7~8个小时左右需要休息2~...
中央空调多长时间清洗一次 1、一般空调开机前清洗一次即可,空调开机中间时段再清洗一次,空调关机时清洗一次,这样比较合理。2、空...
中央空调氟利昂多久加一次 看空调制热和制冷程度,很多人的观点认为氟利昂必须一年放一次,其实这个观点是错误的,理解上面有点偏差,...