MCPcopy Create free account
hub / github.com/0opslab/opslabJutil / sendPost

Method sendPost

src/main/java/com/opslab/helper/HttpHelper.java:178–251  ·  view source on GitHub ↗

发起POST请求 @param httpUrl @param param @return

(String httpUrl, String param)

Source from the content-addressed store, hash-verified

176 * @return
177 */
178 public static String sendPost(String httpUrl, String param) {
179 HttpURLConnection connection = null;
180 InputStream is = null;
181 OutputStream os = null;
182 BufferedReader br = null;
183 String result = null;
184 try {
185 URL url = new URL(httpUrl);
186 // 通过远程url连接对象打开连接
187 connection = (HttpURLConnection) url.openConnection();
188 // 设置连接请求方式
189 connection.setRequestMethod("POST");
190 // 设置连接主机服务器超时时间:15000毫秒
191 connection.setConnectTimeout(15000);
192 // 设置读取主机服务器返回数据超时时间:60000毫秒
193 connection.setReadTimeout(60000);
194
195 // 默认值为:false,当向远程服务器传送数据/写数据时,需要设置为true
196 connection.setDoOutput(true);
197 // 默认值为:true,当前向远程服务读取数据时,设置为true,该参数可有可无
198 connection.setDoInput(true);
199 // 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。
200 connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
201 // 设置鉴权信息:Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0
202 //connection.setRequestProperty("Authorization", "");
203 // 通过连接对象获取一个输出流
204 os = connection.getOutputStream();
205 // 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的
206 os.write(param.getBytes());
207 // 通过连接对象获取一个输入流,向远程读取
208 if (connection.getResponseCode() == 200) {
209 is = connection.getInputStream();
210 // 对输入流对象进行包装:charset根据工作项目组的要求来设置
211 br = new BufferedReader(new InputStreamReader(is, Opslab.UTF_8));
212
213 StringBuilder sbf = new StringBuilder();
214 String temp;
215 // 循环遍历一行一行读取数据
216 while ((temp = br.readLine()) != null) {
217 sbf.append(temp);
218 sbf.append("\r\n");
219 }
220 result = sbf.toString();
221 }
222 } catch (Exception e) {
223 e.printStackTrace();
224 } finally {
225 if (null != br) {
226 try {
227 br.close();
228 } catch (IOException e) {
229 e.printStackTrace();
230 }
231 }
232 if (null != os) {
233 try {
234 os.close();
235 } catch (IOException e) {

Callers 1

testPostMethod · 0.95

Calls 2

writeMethod · 0.45
toStringMethod · 0.45

Tested by 1

testPostMethod · 0.76