代码问题十:post请求传参和返回

调用例子

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

* 发送post请求
* 分开设置请求和响应编码,防止响应报文中文乱码
* @param urlPath 请求地址
* @param content 传参内容
* @param connectTimeout
* @param readTimeout
* @param reqCharset 请求编码格式
* @param respCharset 响应编码格式
* @return 返回字符串
* @throws Exception
*/

public static String (String urlPath, String content, int connectTimeout, int readTimeout, String reqCharset,String respCharset) throws Exception {
try {
URL url = new URL(urlPath);
URLConnection urlConnection = url.openConnection();
System.setProperty("sun.net.client.defaultConnectTimeout", connectTimeout + "");
System.setProperty("sun.net.client.defaultReadTimeout", readTimeout + "");
urlConnection.setRequestProperty("Content-Type", "text/plain;charset=" + reqCharset);
HttpURLConnection httpUrlConnection = (HttpURLConnection) urlConnection;
httpUrlConnection.setDoOutput(true);
httpUrlConnection.setDoInput(true);
httpUrlConnection.setUseCaches(false);
httpUrlConnection.setRequestMethod("POST");
System.out.println("http开始连接");
httpUrlConnection.connect();
System.out.println("http已连接");
OutputStream outStrm = httpUrlConnection.getOutputStream();
// 建立输入流,向指向的URL传入参数
outStrm.write(content.getBytes(reqCharset));
outStrm.flush();
outStrm.close();
// 获得响应状态
int resultCode = httpUrlConnection.getResponseCode();
if (HttpURLConnection.HTTP_OK == resultCode) {
System.out.println("HTTP_OK");
InputStream in = urlConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in, respCharset));
StringBuffer temp = new StringBuffer();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
temp.append(line).append("rn");
}
bufferedReader.close();
return temp.toString();
} else {
throw new RuntimeException("调用接口失败!HTTP状态:" + resultCode);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}