原生POST請求並接受處理返回值

package com.example.study.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
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 java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

public class Post {
    public static void main(String[] args) {
        JSONObject [] paras = new JSONObject[2];
        // TODO Auto-generated method stub
        JSONObject jsonObject1 = new JSONObject();
        JSONObject jsonObject2 = new JSONObject();
        jsonObject1.put("appointNo", "212122");
        jsonObject1.put("approvalStatus", "455");
        jsonObject2.put("appointNo", "123224");
        jsonObject2.put("approvalStatus", "66");
        paras[0]=jsonObject1;
        paras[1]=jsonObject2;
        System.out.println("這是第一個json對象"+JSON.toJSONString(paras));
        String result = HttpPost(paras, "http://59.60.9.13:8131/yms-open-api-web/api/appointOrder/approvalResultReceived.shtml");
        System.out.println(result);
    }

    public static String HttpPost(JSONObject [] paras, String url){
        String result = "";
        HttpPost post = new HttpPost(url);
        try{
            CloseableHttpClient httpClient = HttpClients.createDefault();
            post.setHeader("Content-Type","application/json;charset=utf-8");
            post.addHeader("Authorization", "Basic YWRtaW46");
            StringEntity postingString = new StringEntity(JSON.toJSONString(paras),"utf-8");
            post.setEntity(postingString);
            CloseableHttpResponse httpResponse =httpClient.execute(post);
            // 獲取響應輸入流
            InputStream inStream = httpResponse.getEntity().getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    inStream, "utf-8"));
            StringBuilder strber = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null)
                strber.append(line + "\n");
            inStream.close();
            result = strber.toString();
        } catch (Exception e){
            System.out.println("請求異常");
            throw new RuntimeException(e);
        } finally{
            post.abort();
        }
        return result;
    }

}

 請求結果和輸出信息

 

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