Java利用飞信接口,可以给好友或者自己发送信息。
1.[代码][Java]代码
package com.crawler.core;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import net.sf.json.JSONObject;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
/**
* API 1.u:手机号 2.p:飞信密码 3.to:发送给谁(手机号或飞信号) 4.m:飞信内容
*/
public class Fetion implements Runnable{
//发送的IP地址
private static final String fetionAddress="http://quanapi.sinaapp.com/fetion.php";
//参数列表
List paramsList;
public void sendMessages(String phoneNumber, String userPass, String target,String messages){
//创建一个HttpClient对象
CloseableHttpClient httpclient = HttpClients.createDefault();
//构造Entity对象,采用UTF-8字符编码
UrlEncodedFormEntity urlEntity = new UrlEncodedFormEntity(paramsList, Consts.UTF_8);
//构造HttpPost对象
HttpPost httpPost = new HttpPost(fetionAddress);
//添加头信息
httpPost.addHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");// 在头文件中设置转码
//设置setEntity(entity)
httpPost.setEntity(urlEntity);
//执行请求
CloseableHttpResponse response = null;
try {
response = httpclient.execute(httpPost);
HttpEntity entity = response.getEntity();
if (entity != null) {
JSONObject jsonData=JSONObject.fromObject(EntityUtils.toString(entity));
System.out.println(jsonData.get("message"));
EntityUtils.consume(entity);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
//关闭response和httpclient
HttpClientUtils.closeQuietly(response);
HttpClientUtils.closeQuietly(httpclient);
}
}
public void run(){
sendMessages(null, null, null, null);
}
/**
* @return the paramsList
*/
public List getParamsList() {
return paramsList;
}
/**
* @param paramsList the paramsList to set
*/
public void setParamsList(List paramsList) {
this.paramsList = paramsList;
}
public static void main(String args[]){
Fetion fetion=new Fetion();
//设置参数信息
List formparams = new ArrayList();
formparams.add(new BasicNameValuePair("u", "13546683075"));
formparams.add(new BasicNameValuePair("p", "CHECKME123"));
formparams.add(new BasicNameValuePair("to", "13146683071"));
formparams.add(new BasicNameValuePair("m","Hello World!"));
fetion.setParamsList(formparams);
//创建线程
Thread fetionThread=new Thread(fetion);
fetionThread.start();
}
}