HttpClient post 請求,認證方式爲HTTP Basic Authorization,並解決返回json中文亂碼問題

package org.jeecg.modules.common;

import java.io.IOException;
import java.nio.charset.Charset;
import org.apache.commons.codec.binary.Base64;
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.ContentType;
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.alibaba.fastjson.JSON;

import net.sf.json.JSONObject;


public class HttpClientWithBasicAuth {

   
    public static void main(String[] args) {
        
        JSONObject pushObject = new JSONObject();
        pushObject.put("iccid", "89860403101830362000");

        send(pushObject);
    }
    
    

    
    private static final String URL = "";
    private static final String APP_KEY = "";
    private static final String SECRET_KEY = "";

        /**
       * 構造Basic Auth認證頭信息
       * 
       * @return
       */
      private static String getHeader() {
        String auth = APP_KEY + ":" + SECRET_KEY;
        byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("US-ASCII")));
        String authHeader = "Basic " + new String(encodedAuth);
        return authHeader;
      }
    

    private static void send(JSONObject pushObject) {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(URL);
        System.out.println("要發送的數據" + JSON.toJSONString(pushObject));
        StringEntity myEntity = new StringEntity(JSON.toJSONString(pushObject), ContentType.APPLICATION_JSON); // 構造請求數據
        post.addHeader("Authorization", getHeader());
        //post.addHeader("Content-Type","application/json;charset=UTF-8");  
        post.setEntity(myEntity); // 設置請求體
        
        String responseContent = null; // 響應內容
        CloseableHttpResponse response = null;
        JSONObject json = null;
        try {
            response = client.execute(post);
            System.out.println(JSON.toJSONString(response));
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = response.getEntity();
                responseContent = EntityUtils.toString(entity, "UTF-8");
                json = JSONObject.fromObject(responseContent);//解決中文亂碼
            }
            
            if (response != null) 
                response.close();
            if (client != null) 
                client.close();
            
            System.out.println("responseContent:" + json);
            
        } catch(ClientProtocolException e) {
            e.printStackTrace();
        } catch(IOException e) {
            e.printStackTrace();
        } 
    }

    
}
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章