Java的http post请求01之HttpURLConnection
阅读原文时间:2023年07月10日阅读:1

package com.ricoh.rapp.ezcx.iwbservice.webservice;

import java.io.BufferedOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.URL;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ricoh.rapp.ezcx.iwbservice.util.Constant;
import com.ricoh.rapp.ezcx.iwbservice.util.Utils;

public class HttpRequest {
private final Logger logger = LoggerFactory.getLogger(HttpRequest.class);

/\*\*  
 \* http请求  
 \*  
 \* @param urlPath  
 \*            请求路径http://127.0.0.1:8080/index  
 \* @param requestStr  
 \*            请求参数  
 \*  
 \*/  
public JSONObject execute(String urlPath, String requestStr) {  
    HttpURLConnection httpConnection = null;  
    try {  
        URL url = new URL(urlPath);  
        httpConnection = (HttpURLConnection) url.openConnection();

        httpConnection.setRequestMethod("POST");  
        httpConnection.setDoOutput(true); // post请求为true;get请求为false并且不用out写入数据  
        httpConnection.setDoInput(true); // 有相应数据  
        httpConnection.setConnectTimeout("3 \* 1000");  
        httpConnection.setReadTimeout("Charset");

        // set http header  
        httpConnection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");  
        httpConnection.setRequestProperty("Charset", "UTF-8");  
        httpConnection.connect();

        // send data  
        OutputStream buf = httpConnection.getOutputStream();  
        buf = new BufferedOutputStream(buf);

        OutputStreamWriter out = new OutputStreamWriter(buf);  
        if (requestStr == null || requestStr.length() == 0) {  
            requestStr = new JSONObject().toString();  
        }  
        out.write(requestStr);  
        out.flush();  
        out.close();

        // receive data  
        InputStream inputStream = httpConnection.getInputStream();  
        if (httpConnection.getResponseCode() != HttpURLConnection.HTTP\_OK) {  
            logger.error("connect ezcs service failed: " + httpConnection.getResponseCode());  
            JSONObject responseJson = new JSONObject();  
            responseJson.put(ResponseKey.KEY\_RESULT,  
                    com.ricoh.rapp.unifiedPlatform.dsdkService.constant.HttpConstant.ResultCode.ERROR\_SERVER\_HTTP\_ERROR);  
            return responseJson;  
        }  
        String response = Utils.convertStreamToString(inputStream, Constant.ENCODING\_UTF\_8);  
        logger.debug("response from ezcs service: " + response);  
        JSONObject responseJson = JSON.parseObject(response);  
        return responseJson;  
    } catch (Exception e) {  
        e.printStackTrace();  
        logger.debug("connect local ezcs service exception: " + e.getMessage());  
        JSONObject responseJson = new JSONObject();  
        if (e instanceof SocketTimeoutException || e instanceof SocketException) {  
            responseJson.put(ResponseKey.KEY\_RESULT,  
                    com.ricoh.rapp.unifiedPlatform.dsdkService.constant.HttpConstant.ResultCode.ERROR\_SERVER\_HTTP\_ERROR);  
        } else {  
            responseJson.put(ResponseKey.KEY\_RESULT,  
                    com.ricoh.rapp.unifiedPlatform.dsdkService.constant.HttpConstant.ResultCode.ERROR\_INNER\_ERROR);  
        }  
        return responseJson;  
    } finally {  
        if (httpConnection != null) {  
            httpConnection.disconnect();  
        }  
    }  
}

public static class ResponseKey {  
    public static final String KEY\_RESULT = "result";  
    public static final String KEY\_REASON = "reason";  
    public static final String KEY\_DATA = "data";  
    public static final String KEY\_EXTRA = "extra";  
}  

}

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章