Always returns when building a network through the use of SMS API to send text messages to call java -41, key to the key, it is only a question mark :(

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/qq_41885819/article/details/100019477

Many do today features a whim confession regularly send text messages to his girlfriend, send SMS interface, but basically charges, excusable. In building a network through SMS platform (http://sms.webchinese.cn/default.shtml) can find the very language of each sample code. I did not use the default version of the jar package, which is loaded directly maven package corresponding to the latest version, then, the question becomes, especially after the 4.0 org.apache.httpcomponents should have been greatly updated, many ways to can not be directly used for a long time to test the return value is -41, according to the platform API may know, is displayed: the phone number is empty, the following is part of the code:

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class SendMessageService {
	// 接口地址
	private Log logger = LogFactory.getLog(this.getClass());
	private HttpClient httpClient = null;
	private HttpPost httpPost = null;
	private long startTime = 0L;
	private long endTime = 0L;
	private int status = 0;
//测试方法
public static void main(String[] args) {
	SendMessageService ac = new SendMessageService("http://utf8.api.smschinese.cn/");
	List<NameValuePair> list = new LinkedList<NameValuePair>();
	//设置用户名
	NameValuePair param1 = new BasicNameValuePair("Uid", "xxx");
	//设置秘钥,这个秘钥不是你用户名密码,要去网站上查看
	NameValuePair param2 = new BasicNameValuePair("Key", "xxx");
	//设置收信人号码
	NameValuePair param3 = new BasicNameValuePair("smsMob", "xxx");
	//设置短信内容,内容中不宜出现空格等特殊符号
	NameValuePair param4 = new BasicNameValuePair("smsText", "xxx");
	list.add(param1);
	list.add(param2);
	list.add(param3);
	list.add(param4);
	System.out.println(ac.post(list));
	System.out.println(ac.getStatus());
	}
	//构造方法
	public SendMessageService(String url) {
		if (url != null) {
			this.apiURL = url;
		}
		if (apiURL != null) {		
			RequestConfig config = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT).build();
			this.httpClient = HttpClients.custom().setDefaultRequestConfig(config).build();
			this.httpPost = new HttpPost(apiURL);
		}
	}
	//调用接口API
	public String post(List<NameValuePair> list) {
		String body = null;
		if (this.httpPost != null & list != null ) {
			try {
				UrlEncodedFormEntity entityParam = new UrlEncodedFormEntity(list, "UTF-8");
		        httpPost.setEntity(entityParam);
				this.startTime = System.currentTimeMillis();
				HttpResponse response = httpClient.execute(this.httpPost);
				this.endTime = System.currentTimeMillis();
				int statusCode = response.getStatusLine().getStatusCode();
				logger.info("statusCode:" + statusCode);
				logger.info("调用API 花费时间(单位:毫秒):" + (this.endTime - this.startTime));
				if (statusCode != HttpStatus.SC_OK) {
					logger.error("Method failed:" + response.getStatusLine());
					this.status = 1;
				}
				// Read the response body
				body = EntityUtils.toString(response.getEntity());
			} catch (IOException e) {
				// 网络错误
				this.status = 3;
			} finally {
				logger.info("调用接口状态:" + this.status);
			}
		}
		return body;
	}
	/**
	 * 0.成功 1.执行方法失败 2.协议错误 3.网络错误
	 * @return the status
	 */
	public int getStatus() {
		return this.status;
	}
	public long getStartTime() {
		return this.startTime;
	}
	public long getEndTime() {
		return this.endTime;
	}
}	

Since I can not recognize the request information in the phone number, that request parameters, then there is definitely a problem in the configuration parameters. So you have to check it out to see httpClient source, according to the inheritance of a scare, finally we found org.apache.http.client.utils.URLEncodedUtils this tool class.

    public static String format(
            final List <? extends NameValuePair> parameters,
            final String charset) {
        return format(parameters, QP_SEP_A, charset);
    }
    public static String format(
            final List <? extends NameValuePair> parameters,
            final char parameterSeparator,
            final String charset) {
        final StringBuilder result = new StringBuilder();
        for (final NameValuePair parameter : parameters) {
            final String encodedName = encodeFormFields(parameter.getName(), charset);
            final String encodedValue = encodeFormFields(parameter.getValue(), charset);
            if (result.length() > 0) {
                result.append(parameterSeparator);
            }
            result.append(encodedName);
            if (encodedValue != null) {
                result.append(NAME_VALUE_SEPARATOR);
                result.append(encodedValue);
            }
        }
        return result.toString();
    }

You can see from the second format method is the parameter name and value is taken out, a middle connection "&", etc., is not nearly what, between the first parameter and the previous URL "?" It? ? Sure enough, when declaring the URL with a question mark directly address the problem: http: //utf8.api.smschinese.cn/ ?, so that after subsequent stitching process in order to properly read a parameter.
In addition, more simple and crude way is direct when declaring the URL, plus the corresponding parameter information, can be one step, but this is not particularly conducive to the maintenance and expansion of the code.

Guess you like

Origin blog.csdn.net/qq_41885819/article/details/100019477