SmsHttp.java 2.53 KB
package com.trash.common.utils.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;


public class SmsHttp {
//发送生信
 public static String postJson(String submitUrl, String json) {
	URL url = null;
	String postResponseStr=null;
	HttpURLConnection httpURLConnection =null;
	BufferedReader getResponseBytes =null;
	PrintWriter printWriter =null;
	StringBuilder sb =null;
	try {
		url = new URL(submitUrl);
		httpURLConnection=(HttpURLConnection) url.openConnection();
		httpURLConnection.setRequestMethod("POST");// 提交模式
		httpURLConnection.setConnectTimeout(10000);//连接超时 单位毫秒
		httpURLConnection.setReadTimeout(60000);//读取超时 单位毫秒
		// 发送POST请求必须设置如下两行
		httpURLConnection.setDoOutput(true);
		httpURLConnection.setDoInput(true);
		//httpURLConnection.setRequestProperty("Accept", "application/json");  

		
		httpURLConnection.setRequestProperty("Content-Type", "text/plain");
		httpURLConnection.setRequestProperty("connection", "Keep-Alive");  
		httpURLConnection.setRequestProperty("Charsert", "UTF-8");  
		//httpURLConnection.setRequestProperty("Content-type", "application/json; charset=utf-8");  
		// 获取URLConnection对象对应的输出流
		printWriter = new PrintWriter(httpURLConnection.getOutputStream());
		printWriter.write(json);
		printWriter.flush();
		//printWriter.close();
		int httpRspCode = httpURLConnection.getResponseCode();
		if (httpRspCode == HttpURLConnection.HTTP_OK) {
			sb = new StringBuilder();
			// 开始获取数据
			getResponseBytes = new BufferedReader(
					new InputStreamReader(httpURLConnection.getInputStream(), "utf-8"));
			String line = null;
			while ((line = getResponseBytes.readLine()) != null) {
				sb.append(line);
			}
			getResponseBytes.close();
			postResponseStr=sb.toString();
		}else{
			postResponseStr="ERR:"+httpRspCode;	
		}
	} catch (Exception e) {
		postResponseStr="ERR:"+e.getMessage();	
		e.printStackTrace();
	}finally {
		if (httpURLConnection != null) {
			try {
				httpURLConnection.disconnect();
			} catch (Exception eee) {
			}
		}
		if (getResponseBytes != null) {
			try {
				getResponseBytes.close();
			} catch (Exception ee) {
			}
		}
		if (printWriter != null) {
			try {
				printWriter.close();
			} catch (Exception eeee) {
			}
		}
		if (sb != null) {
			try {
				sb=null;
			} catch (Exception eeeee) {
			}
		}
	}
	System.out.print("sms sends post-->["+postResponseStr+"] json:"+json);
	return postResponseStr;
}

}