POST通用
package com.hongware.uitl;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* HTTP API调用辅助类
*
* @author leo
*
*/
public class HttpApiUitl {
public static String httpPost(String requestUrl,Map params,String data,String charset,String contentType,int conTimeout,int readTimeout){
URL url = null;
try {
if(params!=null&&!params.isEmpty()) {
StringBuffer sb = new StringBuffer(requestUrl).append("?");
Set keys = params.keySet();
for(String key : keys) {
Object value = params.get(key);
sb.append(key).append("=").append(value).append("&");
}
requestUrl = sb.substring(0,sb.length()-1);
}
url = new URL(requestUrl);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");// 提交模式
httpURLConnection.setConnectTimeout(conTimeout);//连接超时 单位毫秒
httpURLConnection.setReadTimeout(readTimeout);//读取超时 单位毫秒
httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
httpURLConnection.setRequestProperty("Charset", charset);
// 设置文件类型:
httpURLConnection.setRequestProperty("Content-Type",contentType);
// 发送POST请求必须设置如下两行
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
// 获取URLConnection对象对应的输出流
PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
// 发送请求参数
if(data!=null) {
printWriter.write(data);//data的参数 流数据
// flush输出流的缓冲
printWriter.flush();
}
//开始获取数据
BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int len;
byte[] arr = new byte[1024];
while((len=bis.read(arr))!= -1){
bos.write(arr,0,len);
bos.flush();
}
bos.close();
return bos.toString(charset);
} catch (Exception e) {
e.printStackTrace();
return "error";
}
}
public static String httpPost(String requestUrl,Map params){
return httpPost(requestUrl, params, "我是中国人", "UTF-8", "application/json; charset=UTF-8", 30000, 3000);
}
public static void main(String[] args) {
String url = "http://192.168.20.69:9000/login";
Map params = new HashMap();
params.put("userId", "test@hongware");
params.put("userIp", "61.152.234.226");
params.put("ati", "0000000000");
String resp = HttpApiUitl.httpPost(url, params);
System.out.println(resp);
}
}