欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

java HttpClient傳輸json格式的參數(shù)實例講解

 更新時間:2021年01月21日 10:57:46   作者:喬葉葉  
這篇文章主要介紹了java HttpClient傳輸json格式的參數(shù)實例講解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧

最近的一個接口項目,傳的參數(shù)要求是json,需要特殊處理一下。

重點是這兩句話:

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

這兩句話的作用與jmeter的設(shè)置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 創(chuàng)建時間: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形式的參數(shù)調(diào)用http接口并對返回的json數(shù)據(jù)進行處理(可以帶文件)

1、參數(shù)的url就是被調(diào)用的地址,map是你要傳的參數(shù)。參數(shù)轉(zhuǎn)成json我使用的是gson方式轉(zhuǎn)換的。

主要使用的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。

如果發(fā)送的post請求想傳送文件,需添加httpmime-4.5.3.jar包,并設(shè)置如下代碼:

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

第一個參數(shù)表示請求字段名,第二個參數(shù)就是文件。

還想添加參數(shù)則

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<String, Object> 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、返回的結(jié)果也可以使用gson轉(zhuǎn)換成對象進行下一步操作。

import com.google.gson.Gson;
public class GsonUtil {
 public static <T> T jsonToObject(String jsonData, Class<T> 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);
 }
}

建立要轉(zhuǎn)成的對象的類。

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、發(fā)送以鍵值對形式的參數(shù)的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);
 // 參數(shù)形式為key=value&key=value
 List<NameValuePair> formparams = new ArrayList<NameValuePair>();
 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);
 }
}

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。

相關(guān)文章

  • eclipse連接不到genymotion問題的解決方案

    eclipse連接不到genymotion問題的解決方案

    今天小編就為大家分享一篇關(guān)于eclipse連接不到genymotion問題的解決方案,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
    2019-03-03
  • 淺談 java中ArrayList、Vector、LinkedList的區(qū)別聯(lián)系

    淺談 java中ArrayList、Vector、LinkedList的區(qū)別聯(lián)系

    ArrayList,Vector底層是由數(shù)組實現(xiàn),LinkedList底層是由雙線鏈表實現(xiàn),從底層的實現(xiàn)可以得出性能問題ArrayList,Vector插入速度較慢,查詢速度較快,而LinkedList插入速度較快,而查詢速度較慢。再者由于Vevtor使用了線程安全鎖,所以ArrayList的運行效率高于Vector
    2015-11-11
  • Kotlin語言編程Regex正則表達式實例詳解

    Kotlin語言編程Regex正則表達式實例詳解

    這篇文章主要為大家介紹了Kotlin語言編程Regex正則表達式實例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-08-08
  • 使用JPA雙向多對多關(guān)聯(lián)關(guān)系@ManyToMany

    使用JPA雙向多對多關(guān)聯(lián)關(guān)系@ManyToMany

    這篇文章主要介紹了使用JPA雙向多對多關(guān)聯(lián)關(guān)系@ManyToMany,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-06-06
  • JAVA8 List<List<Integer>> list中再裝一個list轉(zhuǎn)成一個list操作

    JAVA8 List<List<Integer>> list中再裝一個list轉(zhuǎn)成一個list操

    這篇文章主要介紹了JAVA8 List<List<Integer>> list中再裝一個list轉(zhuǎn)成一個list操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-08-08
  • SSM如何實現(xiàn)在Controller中添加事務(wù)管理

    SSM如何實現(xiàn)在Controller中添加事務(wù)管理

    這篇文章主要介紹了SSM如何實現(xiàn)在Controller中添加事務(wù)管理,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-02-02
  • java實現(xiàn)身份證號碼驗證的示例代碼

    java實現(xiàn)身份證號碼驗證的示例代碼

    這篇文章主要為大家詳細介紹了如何利用java語言實現(xiàn)身份證號碼驗證的功能,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下
    2023-09-09
  • Spring中ClassPath指的是哪些地方

    Spring中ClassPath指的是哪些地方

    在Spring應(yīng)用中,ClassPath指的是應(yīng)用程序的類加載路徑,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2024-06-06
  • Java線程Timer定時器用法詳細總結(jié)

    Java線程Timer定時器用法詳細總結(jié)

    在本篇文章里小編給大家整理的是關(guān)于Java線程Timer定時器用法詳細總結(jié)內(nèi)容,需要的朋友們學習下吧。
    2020-02-02
  • Java選擇排序和垃圾回收機制詳情

    Java選擇排序和垃圾回收機制詳情

    這篇文章主要介紹Java選擇排序和垃圾回收機制,創(chuàng)建對象就會占據(jù)內(nèi)存,如果程序在執(zhí)行過程中不能再使用某個對象,這個對象是徒耗內(nèi)存的垃圾,下面來看看文章具體內(nèi)容吧
    2021-10-10

最新評論