`
baggio1024
  • 浏览: 63488 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
文章分类
社区版块
存档分类

用HttpURLConnection访问web页面.中文乱码的解决

阅读更多
import java.io.OutputStream;
import java.net.*;
import java.util.Date;
import java.text.*;


public class SendInfo2 {
	public static void main(String[] args) {
		boolean b = false;
		String time = "";
		try {
			DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 
		    time = df.format(new Date()); //使用特定格式显示日期和时间
			b = sendBgtMessages("李斯提交了测试",time);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally{
			System.out.print("212---"+time+"--"+b);
		}	
	}
	//短信发送功能
	public static boolean sendBgtMessages(String msg,String send_time) throws Exception{
		boolean b = false;

		
		String address = "http://***/send.jsp";
		StringBuffer sb = new StringBuffer(); 
        sb.append("mobile=13788889999");   
        sb.append("&msgcontent="+msg); 
        sb.append("&sendtime="+send_time);
		b = openConnection(address,sb); 

		return b;
	}
	//访问http链接
	public static boolean openConnection(String address,StringBuffer params) throws Exception {   
		int HttpResult;
		URL url = new URL(address);  
		//返回一个 URLConnection 对象,它表示到 URL 所引用的远程对象的连接。   
		HttpURLConnection urlconn = (HttpURLConnection)url.openConnection();   
		
		urlconn.setDoOutput(true);
		urlconn.setRequestMethod("POST");

		
		//打开到此 URL 引用的资源的通信链接(如果尚未建立这样的连接)。
		urlconn.connect(); 
        //post信息  ,这步很重要,不然就乱码 
	     OutputStream os = urlconn.getOutputStream();   
	     os.write(params.toString().getBytes("utf-8"));   
	     os.close(); 
	     
	  
		//获取该动态链接响应的状态码   
		HttpResult = urlconn.getResponseCode();   
		//判断该动态链接的响应是否能正确连接   
		if (HttpResult != HttpURLConnection.HTTP_OK) {   
  			return false;
		} else {   
            return true;
		}   
  
	}
	
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics