欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

原生POST请求并接受处理返回值

程序员文章站 2022-07-07 09:06:54
...
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;
    }

}

 请求结果和输出信息

原生POST请求并接受处理返回值