java - HttpURLConnection c = URL.openConnection(); c.setRequestProperty() Doesn't work -


this code here normal java application not android application, designed send c2dm messages device your_registration_string developer auth_key, problem described below

import java.io.bufferedreader; import java.io.ioexception; 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 c2dmsendmessage {     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";      // registration hardcoded     private final static string your_registration_string = "apa91bgf8gkfmn_sbp_hossaiqummlwodiqvsqkbbqxv2wsadq51gbixinaguk1u_vdicz7izvaq6tvu8kxgsiq7biky_7f04id00sums8h3ygxbskd6jjg";      public static void main(string[] args) throws exception {         httpsurlconnection.setdefaulthostnameverifier(new hostnameverifier() {              @override             public boolean verify(string arg0, sslsession arg1) {                 // todo auto-generated method stub                 return true;             }         });         string auth_key = "dqaaaa4baadab7bdi6ky9pj11eriy0r1taeynlk6atspxzziecih_vdywlhejcvmkxjh6grasgplb0wtagmwik9cjsbmt3upjnz86trynvfoknkn45ork29asr2he-jeo1y4evcuutopnbbix2kzoeey2ulyxyoqix7owswb4cjs3xyrb7qcmqxmv3yiiaf8ko0sav7-nspcsi3tv3lisrz_bwqscvghwxt6kz_pzwjh7442cpmfzhoyxsgdanqod8eyphjhmnqk_txwwfeifj66jsi90bpypkvux_zubomskvzp3gbckrk9isnjrsupluen46ngrzl2ubg9i9v-wjufbgg1abxqa1owfdkeewxwxapuvqr1-g";         // send sync message android device.         stringbuilder postdatabuilder = new stringbuilder();         postdatabuilder.append(param_registration_id).append("=")                 .append(your_registration_string);          // if (delaywhileidle) {         // postdatabuilder.append("&").append(param_delay_while_idle)         // .append("=1");         // }         postdatabuilder.append("&").append(param_collapse_key).append("=")                 .append("0");          postdatabuilder.append("&").append("data.payload").append("=")                 .append(urlencoder.encode("lars war hier", utf8));          byte[] postdata = postdatabuilder.tostring().getbytes(utf8);          // hit dm url.          url url = new url("https://android.clients.google.com/c2dm/send");          httpurlconnection conn = (httpurlconnection) url.openconnection();         conn.setdooutput(true);         conn.setusecaches(false);         conn.setrequestmethod("post");         conn.setrequestproperty("content-type",                 "application/x-www-form-urlencoded;charset=utf-8");         conn.setrequestproperty("content-length",                 integer.tostring(postdata.length));         conn.setrequestproperty("authorization", "googlelogin auth="                 + auth_key);         system.out.println(conn.getrequestproperties());         outputstream out = conn.getoutputstream();         out.write(postdata);         out.close();          int responsecode = conn.getresponsecode();          system.out.println(string.valueof(responsecode));         // validate response code          if (responsecode == 401 || responsecode == 403) {             // token old - return false retry later,             // fetch token             // db. happens if password changed or token             // expires. either admin             // updating token, or update-client-auth received             // server,             // , next retry 1 database.             system.out.println("unauthorized - need token");         }          // check updated token header         string updatedauthtoken = conn.getheaderfield(update_client_auth);         if (updatedauthtoken != null && !auth_key.equals(updatedauthtoken)) {             system.out.println("got updated auth token datamessaging servers: "                             + updatedauthtoken);         }          string responseline = new bufferedreader(new inputstreamreader(                 conn.getinputstream())).readline();          // note: *must* use exponential backoff if receive 503         // response code.         // since app engine's task queue mechanism automatically         // tasks         // return non-success error codes, not explicitly         // implemented here.         // if weren't using app engine, we'd need manually implement         // this.         if (responseline == null || responseline.equals("")) {             system.out.println("got " + responsecode                     + " response google ac2dm endpoint.");             throw new ioexception(                     "got empty response google ac2dm endpoint.");         }          string[] responseparts = responseline.split("=", 2);         if (responseparts.length != 2) {             system.out.println("invalid message google: " + responsecode                     + " " + responseline);             throw new ioexception("invalid response google "                     + responsecode + " " + responseline);         }          if (responseparts[0].equals("id")) {             system.out.println("successfully sent data message device: "                     + responseline);         }          if (responseparts[0].equals("error")) {             string err = responseparts[1];             system.out.println("got error response google datamessaging endpoint: "                             + err);             // no retry.             throw new ioexception(err);         }     } } 

in code above i'm attempting send c2dm message it's irrelevant

url url = new url("https://android.clients.google.com/c2dm/send");  httpurlconnection conn = (httpurlconnection) url.openconnection(); conn.setdooutput(true); conn.setusecaches(false); conn.setrequestmethod("post"); conn.setrequestproperty("content-type","application/x-www-form-urlencoded;charset=utf-8"); conn.setrequestproperty("content-length",integer.tostring(postdata.length)); conn.setrequestproperty("authorization", "googlelogin auth="+ auth_key); system.out.println(conn.getrequestproperties()); 

in portion have repeated attempting set request properties 3 of them 1 ever reaches hashmap in conn output :

{content-type=[application/x-www-form-urlencoded;charset=utf-8]}

i don't understand how code can run if it's on it's own lines , not work part of bigger code

i tried addrequestproperty

thanks in advance

instead of setting content-length in request property, use setfixedlengthstreamingmode(postdata.length);

according source httpurlconnection , content-length "restricted header":

146       /* 147        * restrict setting of request headers through public api 148        * consistent javascript xmlhttprequest2 few 149        * exceptions. disallowed headers silently ignored 150        * backwards compatibility reasons rather throwing 151        * securityexception. example, applets set 152        * host header since old jres did not implement http 1.1. 153        * additionally, header starting sec- 154        * disallowed. 155        * 156        * following headers allowed historical reasons: 157        * 158        * accept-charset, accept-encoding, cookie, cookie2, date, 159        * referer, te, user-agent, headers beginning proxy-. 160        * 161        * following headers allowed in limited form: 162        * 163        * connection: close 164        * 165        * see http://www.w3.org/tr/xmlhttprequest2. 166        */ 167       private static final boolean allowrestrictedheaders; 168       private static final set<string> restrictedheaderset; 169       private static final string[] restrictedheaders = { 170           /* restricted xmlhttprequest2 */ 171           //"accept-charset", 172           //"accept-encoding", 173           "access-control-request-headers", 174           "access-control-request-method", 175           "connection", /* close allowed */ 176           "content-length", 177           //"cookie", 178           //"cookie2", 179           "content-transfer-encoding", 180           //"date", 181           //"expect", 182           "host", 183           "keep-alive", 184           "origin", 185           // "referer", 186           // "te", 187           "trailer", 188           "transfer-encoding", 189           "upgrade", 190           //"user-agent", 191           "via" 192       }; 

so, setting content-length silently ignored.

authorization blocked being returned security purposes:

249       // following http request headers should not have values 250       // returned security reasons. 251       private static final string[] exclude_headers = { 252               "proxy-authorization", 253               "authorization" 254       }; 255    256       // exclude system cookies when might set 257       private static final string[] exclude_headers2= { 258               "proxy-authorization", 259               "authorization", 260               "cookie", 261               "cookie2" 262       }; 

so if set authorization header, won't when query headers.


Comments

Popular posts from this blog

c++ - Is it possible to compile a VST on linux? -

java - Output of Eclipse is rubbish -

jquery - Confused with JSON data and normal data in Django ajax request -