/**
* 发送主要方法,异常捕获
*
* @param post
* @param code
* @return
*/
public static String doHttpRequest(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
// URLConnection conn = realUrl.openConnection();
HttpURLConnection connection = (HttpURLConnection)realUrl.openConnection();
connection.addRequestProperty("Content-Type", "application/json;charset=UTF-8");
connection.addRequestProperty("User-Agent", "mytest");
connection.setConnectTimeout(60000);
connection.setReadTimeout(60000);
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.getOutputStream().write(param.getBytes("utf8"));
// connection.setRequestProperty("Content-Type", "application/json");
int status = connection.getResponseCode();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));
StringBuffer message = new StringBuffer();
while (reader.ready()) {
message.append(reader.readLine());
}
reader.close();
connection.connect();
if (status == 200) {
return message.toString();
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!"+e);
e.printStackTrace();
}
//使用finally块来关闭输出流、输入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return result;
}
记:
① connection.addRequestProperty("Content-Type", "application/json;charset=UTF-8");如果是json数据这一个属性不添加,会让接收方收不到数据。
② 如果json数据以map<"String, object"> 的形式组装,当key对应得value为null的时候,会报错,如果以jsonobject.getbytes()以流的形式返回就不会出现这种问题。