我使用与 winapi 一起使用的桌面程序开发了一个 android 应用程序,并且我尝试在没有应用程序服务器的情况下访问 google GCM 服务器。我找到了一个很好的例子,而且效果很好。但我需要通过 winapi 应用程序访问 GCM 服务器。我还开发了 android 应用程序,这有助于我理解如何使用这个示例,但是我无法转换为 winapi java 并且 winapi 是如此不同,而且我从未使用过诸如 Get、Post 之类的 winapi http 连接之类的东西。
...来人帮帮我。
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
public class TestSender {
static String gcmURL = "https://android.googleapis.com/gcm/send";
static String gcmRegID = "device register ID";
static String gcmAuthToken = "GCM sever Access Key";
public static void main(String[] args) {
try {
sender(gcmRegID, gcmAuthToken, "Test MSG");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void sender(String regId, String authToken, String msg)
throws Exception {
StringBuffer postDataBuilder = new StringBuffer();
postDataBuilder.append("registration_id=" + regId); // register ID
postDataBuilder.append("&collapse_key=1");
postDataBuilder.append("&delay_while_idle=1");
postDataBuilder.append("&data.msg=" + URLEncoder.encode(msg, "UTF-8"));
byte[] postData = postDataBuilder.toString().getBytes("UTF8");
URL url = new URL(gcmURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
HttpsURLConnection
.setDefaultHostnameVerifier(new FakeHostnameVerifier());
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"application/x-www-formurlencoded;charset=UTF-8");
conn.setRequestProperty("Content-Length",
Integer.toString(postData.length));
conn.setRequestProperty("Authorization", "key=" + gcmAuthToken);
OutputStream out = conn.getOutputStream();
out.write(postData);
out.close();
conn.getInputStream();
System.out.println("postData : " + postDataBuilder.toString());
String reponseLine = new BufferedReader(new InputStreamReader(
conn.getInputStream())).readLine();
System.out.println("responseLine : " + reponseLine);
}
private static class FakeHostnameVerifier implements HostnameVerifier {
public boolean verify(String hostname, SSLSession session) {
return true;
}
}
}