httpUtil第三方请求工具

第三方请求工具

package com.odfly.module.costpay.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpUtil {
    public void httpRequest() {
        HttpURLConnection httpURLConnection = null;
        BufferedReader in = null;
        PrintWriter out = null;
        //        OutputStreamWriter out = null;
        JSONObject result = new JSONObject();
        String urlAddress = "";//请求url
        String param = "";//请求参数
        try {
            URL url = new URL(urlAddress);
            httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoInput(true);
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setRequestProperty("Content_Type", "application/json");
            httpURLConnection.setRequestProperty("Accept_Charset", "UTF-8");
            httpURLConnection.setRequestProperty("contentType", "UTF-8");
            //发送POST请求参数
            out = new PrintWriter(httpURLConnection.getOutputStream());
//            out = new OutputStreamWriter(httpURLConnection.getOutputStream(),"utf-8");
            out.write(param);
//            out.println(strReqJsonStr);
            out.flush();
            //读取响应
            if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                StringBuffer content = new StringBuffer();
                String tempStr = null;
                in = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
                while ((tempStr = in.readLine()) != null) {
                    content.append(tempStr);
                }
                //转换成json对象
                com.alibaba.fastjson.JSONObject respJson = JSON.parseObject(content.toString());
                String resultCode = respJson.getString("errCode");
                System.out.println(resultCode);
            } else {

            }
        } catch (Exception e) {
            e.printStackTrace();

        } finally {
            if (out != null) {
                out.close();
            }
            httpURLConnection.disconnect();
        }
    }
}

猜你喜欢

转载自blog.csdn.net/mxlgslcd/article/details/83416699