2012-01-18 60 views

回答

1

解決了它。

pushClient類:

public static void main(String[] args) 
{ 
    try 
    { 
     String responseString = ""; 
     String outputString = ""; 
     String username = "Application Key"; 
     String password = "Application secret"; 
     Authenticator.setDefault(new MyAuthenticator(username,password)); 

     URL url = new URL("https://go.urbanairship.com/api/push/"); 
     URLConnection urlConnection = url.openConnection(); 
     HttpURLConnection httpConn = (HttpURLConnection)urlConnection; 
     ByteArrayOutputStream bout = new ByteArrayOutputStream(); 

     String postdata = "{\"android\": {\"alert\": \"Hello from JAVA!\"}, \"apids\": [\"APID\"]}"; 
     byte[] buffer = new byte[postdata.length()]; 
     buffer = postdata.getBytes("UTF8"); 

     bout.write(buffer); 
     byte[] b = bout.toByteArray(); 
     httpConn.setRequestProperty("Content-Length",String.valueOf(b.length)); 

     httpConn.setRequestProperty("Content-Type", "application/json"); 
     httpConn.setRequestMethod("POST"); 

     httpConn.setDoOutput(true); 
     httpConn.setDoInput(true); 

     OutputStream out = httpConn.getOutputStream(); 
     out.write(b); 
     out.close(); 

     InputStreamReader isr = new InputStreamReader(httpConn.getInputStream()); 
     BufferedReader in = new BufferedReader(isr); 

     while ((responseString = in.readLine()) != null) 
     { 
      outputString = outputString + responseString; 
     } 
     System.out.println(outputString); 

    } 
    catch (MalformedURLException e) 
    { 
     e.printStackTrace(); 
    } 
    catch (IOException e1) 
    { 
     e1.printStackTrace(); 
    } 
} 

MyAuthenticator類:

private String user; 
    private String passwd; 

    public MyAuthenticator(String user, String passwd) 
    { 
     this.user = user; 
     this.passwd = passwd; 
    } 

    protected PasswordAuthentication getPasswordAuthentication() 
    { 
     return new PasswordAuthentication(user, passwd.toCharArray()); 
    } 
+0

我試過了這個例子,我m到處ConnectionException, – 2013-05-07 15:17:42

+0

檢查,如果互聯網是工作 千萬記得要加 <使用許可權的android :名稱= 「android.permission.INTERNET對」> 2013-07-03 07:53:37