我想要一个HTTP-POST发送到谷歌云消息传递服务。 我已经安装了正确的按键,一切工作时我使用PHP脚本发送推送通知到我的手机。
但我的Java httpPost只返回一个401响应。 我已按照给出的说明Android开发者 ,但我仍然得到了烦人的401我错了分配头字段?
我的代码:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
public class Server {
public static void main(String[] args) throws IOException {
String url = "https://android.googleapis.com/gcm/send";
HttpClient client = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(url);
HttpPost httppost = new HttpPost("https://android.googleapis.com/gcm/send");
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("registration_id=", "MY_DEVICE_GSM_REG_ID"));
urlParameters.add(new BasicNameValuePair("data=", "Type=value,Lat=58.365547,Long=8.613235,Comment=value"));
httppost.setHeader("Authorization",
"key=MY_API_AUTH_FROM_GOOGLE_API_CONSOLE_BROWSER_TOKEN");
httppost.setHeader("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
post.setEntity(new UrlEncodedFormEntity(urlParameters, "UTF-8"));
HttpResponse response = client.execute(post);
System.out.println("Response Code : "
+ response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
}
}