Java 使用servlet在getOutputStream()函数推送通知时自动停止执行

Java 使用servlet在getOutputStream()函数推送通知时自动停止执行,java,httpclient,http-post,Java,Httpclient,Http Post,在服务器端获取推送通知时出现问题。我使用C2DM服务器连接来实现推送通知。它在android上运行良好,但在Java Servecr中不起作用。我能够获取注册ID和身份验证代码,但当涉及到行时,处理停止: OutputStream out = conn.getOutputStream(); 它不扔任何东西,只是停下来 如果有人对此有解决方案,请指导我。我正在添加整个代码,这样您就可以查看并告诉我在获得结果时哪里出错了 import org.apache.http.client.methods.

在服务器端获取推送通知时出现问题。我使用C2DM服务器连接来实现推送通知。它在android上运行良好,但在Java Servecr中不起作用。我能够获取注册ID和身份验证代码,但当涉及到行时,处理停止:

OutputStream out = conn.getOutputStream();
它不扔任何东西,只是停下来

如果有人对此有解决方案,请指导我。我正在添加整个代码,这样您就可以查看并告诉我在获得结果时哪里出错了

import org.apache.http.client.methods.HttpPost;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.HttpsURLConnection;
import javax.print.DocFlavor.INPUT_STREAM;
import org.apache.http.HttpClientConnection;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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.DefaultHttpClientConnection;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
public class Server {
    private static String key=null;
    //    private final static String AUTH = "authentication";
    private static final String UPDATE_CLIENT_AUTH = "Update-Client-Auth";
    public static final String PARAM_REGISTRATION_ID = "registration_id";
    public static final String PARAM_DELAY_WHILE_IDLE = "delay_while_idle";
    public static final String PARAM_COLLAPSE_KEY = "collapse_key"; 
    private static final String UTF8 = "UTF-8";
    private static String Authcode = null;

    // Registration is currently hardcoded
    private final static String YOUR_REGISTRATION_STRING = "reg id";

    public void getAuthentification() {
        System.out.println("check");
        //HttpPost post = new HttpPost("http://www.google.com/accounts/ClientLogin");
        try {
            System.getProperties().put("proxySet", true);
            System.getProperties().put("proxyHost","proxy" );
            System.getProperties().put("proxyPort","8080");
            System.out.println("getAuthentication method called****************************");
            URL url=new URL("https://www.google.com/accounts/ClientLogin");

            URLConnection connection=url.openConnection();
            connection.setDoOutput(true);

            HttpURLConnection conn=(HttpURLConnection)connection;
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setUseCaches(true);

            StringBuilder content = new StringBuilder();
            content.append("Email=").append("xyz@gmail.com");
            content.append("&Passwd=").append("asdfgt");
            content.append("&service=").append("ac2dm");
            content.append("&source=").append("MY_APP-V0.1");
            content.append("&accountType=").append("HOSTED_OR_GOOGLE");

            OutputStream out = conn.getOutputStream();
            out.write(content.toString().getBytes("UTF-8"));
            out.close();

            int res = conn.getResponseCode();
            System.out.println(res + "Success");
            StringBuffer resp = new StringBuffer();

            if(res == HttpsURLConnection.HTTP_OK){
                InputStream in = conn.getInputStream();
                BufferedReader rd = new BufferedReader(new InputStreamReader(in));
                String line = "";
                while ((line = rd.readLine()) != null) {
                    System.out.println(line);
                    System.out.println("inside");
                    if (line.startsWith("Auth=")) {
                        Authcode = line.substring(5);
                        resp.append(line.substring(5));
                        System.out.println(line.substring(5));
                        System.out.println("something to be done here..");

                    }
                }
                rd.close();
            }
        }
    }
    public void sendMessage() {
        try {
            System.out.println(YOUR_REGISTRATION_STRING);
            System.out.println("Authcode = " + Authcode);
            System.getProperties().put("proxySet", true);
            System.getProperties().put("proxyHost","proxy" );
            System.getProperties().put("proxyPort","8080");
            URL url1 = new URL("https://android.apis.google.com/c2dm/send");
            System.out.println("here2.5");
            HttpURLConnection conn1 = (HttpURLConnection) url1.openConnection();
            System.out.println("here2.6");
            conn1.setDoInput(true);
            conn1.setDoOutput(true);
            conn1.setUseCaches(false);            
            conn1.setRequestMethod("POST");

            conn1.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
            conn1.setRequestProperty("Authorization", "GoogleLoginauth="+ Authcode);
            System.out.println("here2.7");
            OutputStream out = conn1.getOutputStream();
            System.out.println("send Message method.");
            String auth_key="n/a";
            if(key!=null) {
                auth_key=Authcode;
            }
            System.out.println("here");
            // Send a sync message to this Android device.
            StringBuilder postDataBuilder = new StringBuilder();
            postDataBuilder.append(PARAM_REGISTRATION_ID)
                .append("=").append(YOUR_REGISTRATION_STRING);
            System.out.println("here1");
            postDataBuilder.append("&").append(PARAM_COLLAPSE_KEY)
                .append("=").append("0");
            System.out.println("here2");
            postDataBuilder.append("&").append("data.payload")
                .append("=").append(URLEncoder.encode("Lars war hier", UTF8));

            byte[] postData = postDataBuilder.toString().getBytes(UTF8);
            conn1.setRequestProperty("Content-Length",
                            Integer.toString(postData.length));
            // Hit the dm URL.
            System.out.println("out created");
            out.write(postData);
            System.out.println("data written");

            out.close();
            System.out.println("here3");
            int responseCode = conn1.getResponseCode();

            System.out.println(String.valueOf(responseCode));
            // Validate the response code

            if (responseCode == 401 || responseCode == 403) {
                // The token is too old - return false to retry later, will
                // fetch the token
                // from DB. This happens if the password is changed or token
                // expires. Either admin
                // is updating the token, or Update-Client-Auth was received by
                // another server,
                // and next retry will get the good one from database.
                System.out.println("C2DM, Unauthorized - need token");
            }
        } catch (Exception ignore) {
            // the editor that corrected the indentation of the code could not find any code here so he closed all methods to have a syntactically correct class.
        }
    }
}

确保您是从后台线程而不是从UI线程将消息发布到url


我希望在这一改变之后,它会起作用。祝你好运

如果这仍然不起作用,您可以查看堆栈跟踪吗?也就是说,使用jstack来显示您的程序正在阻止的位置?content.append\r\n;可能需要业务逻辑。顺便说一句,新的InputStreamReader…,UTF-8`通常使用Firefox+TamperData或其他工具来检查常规数据交换。