最近公司因为服务器原因暂时无法使用,但是设备要向客户端发送离线消息。于是花了我两天时间写了这么一点,使用极光服务器发送消息的功能。向服务器发送消息。大牛一看就懂,写下来一方面为了保存一下,如果谁有需要的也可以看看
package com.example.jija.okhttp;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.util.concurrent.TimeUnit;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
private String url = "https://api.jpush.cn/v3/push";
private String enToStr;
private String Name;
private EditText name;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//换成自己的AppKey和Master Secret
String string = "123456:123456";
enToStr = Base64.encodeToString(string.getBytes(), Base64.NO_WRAP);
name = (EditText) findViewById(R.id.name);
Button send = (Button) findViewById(R.id.send);
send.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new Thread() {
@Override
public void run() {
try {
postJson();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
}
});
}
public final static int CONNECT_TIMEOUT = 60;
public final static int READ_TIMEOUT = 100;
public final static int WRITE_TIMEOUT = 60;
public void postJson() throws Exception {
Name = name.getText().toString();
OkHttpClient okHttp = new OkHttpClient.Builder()
.readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)//设置读取超时时间
.writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)//设置写的超时时间
.connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)//设置连接超时时间
.build();
// private String name=”{‘platform’:’all’,’audience’:’all’,’notification’:{‘alert’:’Hi,baiyanfei!’}}”;
final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
RequestBody requestBody = new FormBody.Builder().add("platform","all")
.add("audience","all")
.add("notification",("{'alert':'"+Name+"'}")).build();
Log.e("========",("{'alert':"+Name+"}"));
Request request = new Request.Builder()
.url(url)
.addHeader("Content-Type", "application/json")
.addHeader("Authorization", "Basic " + enToStr)
.post(requestBody)
.build();
Log.i("123", enToStr);
okhttp3.Call call = okHttp.newCall(request);
Response response = call.execute();
if (response.isSuccessful()) {
Log.i("123456", "成功");
}else{
Log.i("123456", "失败");
}
}
}