java类模拟浏览器post请求

package Junit;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.client.ClientProtocolException;


public class Demo {
	public static void main(String[] args) {
        
		try {
			String url = "http://localhost:8080/PuTian/sms.do?method=sendActionSms";
			PostMethod postMethod = new PostMethod(url);
			postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
			//填入各个表单域的值
			NameValuePair[] data = {
									new NameValuePair("mobileNo", "188xxxxxxx"),
									new NameValuePair("messageContext","中文测试") ,
									new NameValuePair("pCode","haixxx") ,
								   };
			postMethod.setRequestBody(data);
			HttpClient httpclient = new HttpClient();
			int statusCode =  httpclient.executeMethod(postMethod);
			if(statusCode == HttpStatus.SC_OK){
				InputStream in = postMethod.getResponseBodyAsStream();
				BufferedReader reader = new BufferedReader(new InputStreamReader(in,postMethod.getResponseCharSet()));
				String inputLine = null ;
				inputLine = reader.readLine();
				if(inputLine==null){
					System.out.println("系统异常");
					return ;
				}
				
				if("true".equals(inputLine)){
					System.out.println("发送成功!");
					return ;
				}else if ("false".equals(inputLine)){
					inputLine = reader.readLine();
					if(inputLine == null || "".equals(inputLine)){
						System.out.println("系统异常");
						return ;
					}
					
					if("1".equals(inputLine)){
						System.out.println("手机号码串不能为空!");
						return ;
					}else if("2".equals(inputLine) ){
						System.out.println("手机号码串格式错误!例:13545781245,13954215487");
						return ;
					}else if("3".equals(inputLine)){
						System.out.println("短信内容不能为空!");
						return ;
					}else if ("5".equals(inputLine)){
						System.out.println("发送失败!");
						return ;
					}else if ("6".equals(inputLine)){
						System.out.println("认证失败!");
						return ;
					}else if("0".equals(inputLine)){
						System.out.println("系统异常!");
						return ;
					}
				}else {
					System.out.println("系统异常");
					return ;
				}
				
			}else{
				System.out.println("网络错误!");
				return ;
			}
			
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值