Java的http post请求01之HttpURLConnection
2024-10-09 21:23:17
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";
}
}
最新文章
- Tomcat:配置SSL
- SQL SERVER中求上月、本月和下月的第一天和最后一天 DATEADD DATEDIFF
- EF-Linq将查询结果转换为List<;string>;
- Gitblit Go
- linux驱动初探之杂项设备(控制两个GPIO口)
- ARM Linux启动代码分析
- ASP.NET Web API 路由
- 记一次 nginx 504 Gateway Time-out
- Cordova WP8 平台安装部署
- Vladik and cards
- 2018年第一篇行动笔记:Reading Log
- php 抽象类 静态 单体设计模式
- JetBrains Rider 2018.1 汉化
- DAY4 if、while和for
- Unity3d学习笔记记录
- (原创)C++11改进我们的程序之简化我们的程序(六)
- GoldenGate搭建与运维
- 【CSAPP笔记】1. 位、字节、整型
- 在Android 开发中使用 SQLite 数据库笔记
- 浅谈 .NET 中的对象引用、非托管指针和托管指针