HttpURLConnection工具类

简介

为了满足各种POST、GET、PUT、DELETE需求.带请求头参数,或者对象参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package com.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.RequestMethod;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class SendHttpUtil {

public static JSONObject doHttp(String urlPath, String param, RequestMethod method,String token) {
try{
URL url=new URL(urlPath);
HttpURLConnection httpConn = (HttpURLConnection)url.openConnection();
//设置参数
httpConn.setConnectTimeout(2000); //超时时间
httpConn.setDoOutput(true); //需要输出
httpConn.setDoInput(true); //需要输入
httpConn.setUseCaches(false); //不允许缓存
httpConn.setRequestMethod(method.toString());//设置方式连接
//设置请求属性
httpConn.setRequestProperty("Content-Type", "application/json");
httpConn.setRequestProperty("Charset", "UTF-8");
httpConn.setRequestProperty("Accept", "*/*");
httpConn.setRequestProperty("Connection", "keep-alive");
if(token!=null&&!"".equals(token)){
httpConn.setRequestProperty("Token", token);
}
httpConn.connect();
//建立输入流,向指向的URL传入参数
if(param!=null&&!"".equals(param)){
DataOutputStream dos=new DataOutputStream(httpConn.getOutputStream());
dos.write(param.getBytes("UTF-8"));
dos.flush();
dos.close();
}
//获得响应状态
int resultCode=httpConn.getResponseCode();
if(HttpURLConnection.HTTP_OK==resultCode||HttpURLConnection.HTTP_CREATED==resultCode){
StringBuffer sb=new StringBuffer();
String readLine=new String();
BufferedReader responseReader=new BufferedReader(new InputStreamReader(httpConn.getInputStream(),"UTF-8"));
while((readLine=responseReader.readLine())!=null){
sb.append(readLine).append("\n");
}
responseReader.close();
return JSON.parseObject(sb.toString());
}else{
System.out.println("请求异常CODE:"+resultCode);
}
}catch (Exception e){
e.printStackTrace();
}
return new JSONObject();
}



//测试方法
public static void main(String[] args) throws Exception{
JSONObject param = new JSONObject();
param.put("objid","132");
param.put("type","123");
param.put("desc", "ces");
System.out.println(SendHttpUtil.doHttp("http://xxx:5008/username="+ URLEncoder.encode("测试", "utf-8"), param.toString(), RequestMethod.POST,null));
}
}
文章作者: 柯熠
文章链接: https://smallkserver.github.io/2020/12/01/httpUtil工具类/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Smallkserver
打赏
  • 微信
  • 支付宝

评论