1发送post请求,参数form表单格式 public static String sendFormHttpReq(String url, Map<String, Object> params) throws IOException { HttpURLConnection conn = null; OutputStreamWriter out = null; InputStream inputStream = null; InputStreamReader inputStreamReader = null; BufferedReader reader = null; StringBuffer result = new StringBuffer(); try { conn = (HttpURLConnection) new URL(url).openConnection(); conn.setInstanceFollowRedirects(false); conn.setReadTimeout(HttpTimeOut); conn.setConnectTimeout(HttpTimeOut); conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("accept", "/"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("Accept-Charset", "UTF-8"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.connect();
out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
out.write(buildQueryParam(params));
out.flush();
inputStream = conn.getInputStream();
inputStreamReader = new InputStreamReader(inputStream);
reader = new BufferedReader(inputStreamReader);
String tempLine = null;
while ((tempLine = reader.readLine()) != null) {
result.append(tempLine);
}
} catch (IOException e) {
Log.infoStackTrace(e);
return null;
} finally {
if(out != null) {
out.close();
}
if(reader != null) {
reader.close();
}
if(inputStreamReader != null) {
inputStreamReader.close();
}
if(inputStream != null) {
inputStream.close();
}
conn.disconnect();
}
Log.debug("响应结果:" + result.toString());
return result.toString();
}
/**
* 将map转换为请求字符串
* @return String
* @param params
* @return action=send&userid=54
* @throws IOException
*/
public static String buildQueryParam(Map<String, Object> params) throws IOException {
if(params == null || params.isEmpty()) {
return null;
}
StringBuffer data = new StringBuffer();
boolean flag = false;
for(Entry<String, Object> entry : params.entrySet()) {
if(flag) {
data.append("&");
} else {
flag = true;
}
data.append(entry.getKey()).append("=").append(entry.getValue());
}
return data.toString();
}
2post请求,参数json格式
public class HttpClientHandle {
private static int HttpTimeOut = 20000; // 连接超时时间(单位:毫秒ms)
private static String Method_Get = "GET"; // get方式
private static String Method_Post = "POST"; // post方式
/**
* httpURLConnection
* @return String 返回结果
* @param param
* 请求参数
* @param serverUrl
* 服务端地址
* @param method
* 请求方式
* @return
*/
public static String sendHttpReq(String param, String sign, String serverUrl, String method) {
BufferedReader br = null;
DataOutputStream out = null;
HttpURLConnection urlcon = null;
try {
URL url = new URL(serverUrl);// 请求的地址
urlcon = (HttpURLConnection) url.openConnection();// 打开连接
urlcon.setInstanceFollowRedirects(false);
urlcon.setReadTimeout(HttpTimeOut);
urlcon.setConnectTimeout(HttpTimeOut);
urlcon.setDoOutput(true);
urlcon.setDoInput(true);
urlcon.setUseCaches(false);
urlcon.setRequestMethod(method);
// urlcon.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
urlcon.setRequestProperty("Content-Type", "application/json;charset=UTF-8");// json格式
// 如果签名不为空,则设置签名参数
if(StringUtil.isNotEmpty(sign)) {
urlcon.setRequestProperty("sign", sign);
}
urlcon.connect();
// 2、发送消息
if(Method_Post.equals(method) && StringUtil.isNotEmpty(param)) {
out = new DataOutputStream(urlcon.getOutputStream());
out.write(param.getBytes("UTF-8"));
out.flush();
}
// 3、接收消息
br = new BufferedReader(new InputStreamReader(urlcon.getInputStream(), "UTF-8"));
String line = br.readLine();
StringBuffer sb = new StringBuffer();
while (null != line) {
sb.append(line);
line = br.readLine();
}
Log.debug("响应结果:" + sb.toString());
return sb.toString();
} catch (IOException e) {
Log.infoStackTrace(e);
return null;
} catch (Exception e) {
Log.infoStackTrace(e);
return null;
} finally {
if(br != null) {
try {
br.close();
br = null;
} catch (IOException e) {
Log.warnStackTrace(e);
}
}
if(out != null) {
try {
out.close();
out = null;
} catch (IOException e) {
Log.warnStackTrace(e);
}
}
urlcon.disconnect();
}
}
/**
* httpURLConnection调用方式(form提交)
*
* @author Nick
* @date 2016年8月20日 下午8:02:16
* @return String
* @param url
* 请求路径
* @param param
* post请求参数,比如action=send&userid=54
* @return
*/
public static String sendFormHttpReq(String url, String param) {
try {
if(ObjectUtil.isNotNull(param)) {
param = new String(param.getBytes("UTF-8"), "ISO-8859-1");
}
} catch (UnsupportedEncodingException e) {
Log.infoStackTrace(e);
}
StringBuffer sb = new StringBuffer();
DataOutputStream out = null;
BufferedReader br = null;
HttpURLConnection urlConn = null;
try {
URL u = new URL(url);// 请求的地址
urlConn = (HttpURLConnection) u.openConnection();// 打开连接
urlConn.setInstanceFollowRedirects(false);
urlConn.setReadTimeout(HttpTimeOut);
urlConn.setConnectTimeout(HttpTimeOut);
urlConn.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
// 必须告诉服务器你发送的数据大小
urlConn.setRequestProperty("Content-length", "" + (ObjectUtil.isNotNull(param) ? param.length() : 0));
urlConn.setDoInput(true);
urlConn.setDoOutput(true);
urlConn.setUseCaches(false);
urlConn.setRequestMethod("POST"); // post请求
urlConn.setRequestProperty("Charset", "UTF-8");
urlConn.connect();
out = new DataOutputStream(urlConn.getOutputStream());
out.writeBytes(ObjectUtil.isNotNull(param) ? param : "");
out.flush();
// 接收消息
String str = null;
br = new BufferedReader(new InputStreamReader(urlConn.getInputStream(), "UTF-8"));
while ((str = br.readLine()) != null) {
sb.append(str);
}
Log.debug("响应结果:" + sb.toString());
return sb.toString();
} catch (IOException e) {
Log.infoStackTrace(e);
return null;
} catch (Exception e) {
Log.infoStackTrace(e);
return null;
} finally {
if(br != null) {
try {
br.close();
br = null;
} catch (IOException e) {
Log.warnStackTrace(e);
}
}
if(out != null) {
try {
out.close();
out = null;
} catch (IOException e) {
Log.warnStackTrace(e);
}
}
urlConn.disconnect();
}
}
/**
* POST方式请求
*
* @param xmlmsg
* @param ServerUrl
* @return
*/
public static String post(String param, String serverUrl) {
return sendHttpReq(param, "", serverUrl, Method_Post);
}
/**
* GET方式请求
*
* @param xmlmsg
* @param ServerUrl
* @return
*/
public static String get(String param, String serverUrl) {
return sendHttpReq(param, "", serverUrl, Method_Get);
}
/**
* 发送带签名的post请求
* @return String
* @param serverUrl
* @param param
* @param sign
* @return
*/
public static String post(String serverUrl, String param, String sign) {
return sendHttpReq(param, sign, serverUrl, Method_Post);
}
/**
* 发送https请求
*
* @param xmlmsg
* @param ServerUrl
* @param method
* @return
*/
public static String sendHttpsReq(String param, String serverUrl, String method) {
DataOutputStream out = null;
BufferedReader br = null;
HttpURLConnection urlcon = null;
try {
// 请求的地址
URL url = new URL(serverUrl);
urlcon = (HttpsURLConnection) url.openConnection();// 打开连接
urlcon.setInstanceFollowRedirects(false);
urlcon.setReadTimeout(HttpTimeOut);
urlcon.setConnectTimeout(HttpTimeOut);
urlcon.setDoOutput(true);
urlcon.setDoInput(true);
urlcon.setUseCaches(false);
urlcon.setRequestMethod(method);
urlcon.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
urlcon.connect();
// 2、发送消息
if(Method_Post.equals(method) && StringUtil.isNotEmpty(param)) {
out = new DataOutputStream(urlcon.getOutputStream());
out.write(param.getBytes("UTF-8"));
out.flush();
}
// 3、接收消息
br = new BufferedReader(new InputStreamReader(urlcon.getInputStream(), "UTF-8"));
String line = br.readLine();
StringBuffer sb = new StringBuffer();
while (null != line) {
sb.append(line);
line = br.readLine();
}
Log.debug("响应结果:" + sb.toString());
return sb.toString();
} catch (IOException e) {
Log.infoStackTrace(e);
return null;
} catch (Exception e) {
Log.infoStackTrace(e);
return null;
} finally {
if(br != null) {
try {
br.close();
br = null;
} catch (IOException e) {
Log.warnStackTrace(e);
}
}
if(out != null) {
try {
out.close();
out = null;
} catch (IOException e) {
Log.warnStackTrace(e);
}
}
urlcon.disconnect();
}
}
public static void main(String args[]) throws Exception {
StringBuffer data = new StringBuffer();
data.append("{\"userLogin\" : \"benson\", \"coName\" : \"MrLiangCo\", \"coNameEn\" : \"MrLiangCo\", "
+ "\"coIndustry\" : \"金融业\", \"coAddress\" : \"深圳\", \"email\" : \"mrliang@163.com\", "
+ "\"userPass\" : \"123456\", \"userPassConfirm\" : \"123456\"}");
String str = HttpClientHandle.post(data.toString(), "http://www.ybolo.net/rest/ExternalLiveService/createCo");
System.out.println(str);
}
}