http请求工具类

http请求工具类

这个一个能自己配置请求url、请求方法、请求的媒体类型信息、请求的参数的http工具类

HttpUtil类

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
package com.fufu.httprequest.tools;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

public class HttpUtil {
public static String httpRequest(String generalUrl,String requestMethod, String contentType, String params)
throws Exception {
String encoding = "UTF-8";
if (generalUrl.contains("nlp")) {
encoding = "GBK";
}
URL url = new URL(generalUrl);
// 打开和URL之间的连接
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(requestMethod);
// 设置通用的请求属性
connection.setRequestProperty("Content-Type", contentType);
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setUseCaches(false);
connection.setDoOutput(true);
connection.setDoInput(true);

// 得到请求的输出流对象
DataOutputStream out = new DataOutputStream(connection.getOutputStream());
out.write(params.getBytes(encoding));
out.flush();
out.close();

// 建立实际的连接
connection.connect();
// 获取所有响应头字段
Map<String, List<String>> headers = connection.getHeaderFields();
// 遍历所有的响应头字段
// for (String key : headers.keySet()) {
// System.err.println(key + "--->" + headers.get(key));
// }
// 定义 BufferedReader输入流来读取URL的响应
BufferedReader in = null;
in = new BufferedReader(
new InputStreamReader(connection.getInputStream(), encoding));
String result = "";
String getLine;
while ((getLine = in.readLine()) != null) {
result += getLine;
}
in.close();
// System.err.println("result:" + result);
return result;
}
}

test方法

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
package com.fufu.httprequest;

import com.fufu.httprequest.tools.HttpUtil;
import net.sf.json.JSONObject;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class HttprequestApplicationTests {

@Test
public void contextLoads() {
try {
String result = HttpUtil.httpRequest("http://localhost:8080/robotservice/visitorRecord/qryVisitedUnit","POST","application/x-www-form-urlencoded","telNum=1555");
JSONObject jobj = JSONObject.fromObject(result);
System.out.println(jobj.toString());
} catch (Exception e) {
e.printStackTrace();
}
}

}

人生两苦:想要却不得,拥有却失去。 –褚禄山
珍惜当下,与君共勉~


本文标题:http请求工具类

文章作者:fufua

发布时间:2018年11月16日 - 10:18:13

最后更新:2018年11月16日 - 10:13:03

原始链接:https://qq1028951741.github.io/2018/11/16/http请求工具类/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

this is end, thank you for reading