<p>προσπαθώ να κάνω <strong>μετά</strong> με <code>httpurlconnection</code> (πρέπει να το χρησιμοποιήσω με αυτόν τον τρόπο, δεν μπορώ να χρησιμοποιήσω <code>httppost</code>) και θα ήθελα να προσθέσω παραμέτρων αυτής της σύνδεσης, όπως</p><pre><code>post.setentity(new urlencodedformentity(nvp)); </code></pre><p>όπου</p><pre><code>nvp = new arraylist&lt;namevaluepair&gt;(); </code></pre><p>έχοντας αποθηκευμένα κάποια δεδομένα. δεν μπορώ να βρω έναν τρόπο να προσθέσω αυτό το <code>arraylist</code> στο <code>httpurlconnection</code> μου που είναι εδώ:</p><pre><code>httpsurlconnection https = (httpsurlconnection) url.openconnection(); https.sethostnameverifier(do\_not\_verify); http = https; http.setrequestmethod("post"); http.setdoinput(true); http.setdooutput(true); </code></pre><p>ο λόγος για αυτόν τον αμήχανο συνδυασμό https και http είναι η ανάγκη να <em> δεν επαληθεύει </em> το πιστοποιητικό. αυτό δεν είναι πρόβλημα, όμως, τοποθετεί το διακομιστή καλά. αλλά πρέπει να το τοποθετήσω με επιχειρήματα.</p><p>καμιά ιδέα?</p><hr><p><strong> δήλωση αποποίησης διπλών όρων: </strong></p><p>πίσω το 2012, δεν είχα ιδέα πώς εισήχθησαν οι παράμετροι σε ένα αίτημα <strong> http post </strong>. είχα κρεμάσει για να <code>namevaluepair</code> γιατί ήταν σε ένα σεμινάριο. αυτή η ερώτηση μπορεί να φαίνεται σαν ένα αντίγραφο, ωστόσο, το 2012 μου διαβάσει ότι <em> <a href="https://stackoverflow.com/questions/4205980/java-sending-http-parameters-via-post-method-easily">άλλο</a> </em> ερώτηση και ήταν <strong>όχι</strong> χρησιμοποιώντας <code>namevaluepair</code>. στην πραγματικότητα δεν λύνει το πρόβλημά μου.</p>
πώς να προσθέσετε παραμέτρους στο httpurlconnection χρησιμοποιώντας post χρησιμοποιώντας το όνομαvaluepair
<p>μπορείτε να λάβετε ροή εξόδου για τη σύνδεση και να γράψετε τη συμβολοσειρά ερώτησης παραμέτρων σε αυτήν.</p><pre><code>url url = new url("http://yoururl.com"); httpsurlconnection conn = (httpsurlconnection) url.openconnection(); conn.setreadtimeout(10000); conn.setconnecttimeout(15000); conn.setrequestmethod("post"); conn.setdoinput(true); conn.setdooutput(true); list&lt;namevaluepair&gt; params = new arraylist&lt;namevaluepair&gt;(); params.add(new basicnamevaluepair("firstparam", paramvalue1)); params.add(new basicnamevaluepair("secondparam", paramvalue2)); params.add(new basicnamevaluepair("thirdparam", paramvalue3)); outputstream os = conn.getoutputstream(); bufferedwriter writer = new bufferedwriter( new outputstreamwriter(os, "utf-8")); writer.write(getquery(params)); writer.flush(); writer.close(); os.close(); conn.connect(); </code></pre><p>...</p><pre><code>private string getquery(list&lt;namevaluepair&gt; params) throws unsupportedencodingexception { stringbuilder result = new stringbuilder(); boolean first = true; for (namevaluepair pair : params) { if (first) first = false; else result.append("&amp;"); result.append(urlencoder.encode(pair.getname(), "utf-8")); result.append("="); result.append(urlencoder.encode(pair.getvalue(), "utf-8")); } return result.tostring(); } </code></pre>
<p>από τη στιγμή που το namevaluepair καταργηθεί. σκέψη του μοιράσματος του κώδικα μου</p><pre><code>public string performpostcall(string requesturl, hashmap&lt;string, string&gt; postdataparams) { url url; string response = ""; try { url = new url(requesturl); httpurlconnection conn = (httpurlconnection) url.openconnection(); conn.setreadtimeout(15000); conn.setconnecttimeout(15000); conn.setrequestmethod("post"); conn.setdoinput(true); conn.setdooutput(true); outputstream os = conn.getoutputstream(); bufferedwriter writer = new bufferedwriter( new outputstreamwriter(os, "utf-8")); writer.write(getpostdatastring(postdataparams)); writer.flush(); writer.close(); os.close(); int responsecode=conn.getresponsecode(); if (responsecode == httpsurlconnection.http\_ok) { string line; bufferedreader br=new bufferedreader(new inputstreamreader(conn.getinputstream())); while ((line=br.readline()) != null) { response+=line; } } else { response=""; } } catch (exception e) { e.printstacktrace(); } return response; } </code></pre><p>....</p><pre><code> private string getpostdatastring(hashmap&lt;string, string&gt; params) throws unsupportedencodingexception{ stringbuilder result = new stringbuilder(); boolean first = true; for(map.entry&lt;string, string&gt; entry : params.entryset()){ if (first) first = false; else result.append("&amp;"); result.append(urlencoder.encode(entry.getkey(), "utf-8")); result.append("="); result.append(urlencoder.encode(entry.getvalue(), "utf-8")); } return result.tostring(); } </code></pre>
<p>εάν δεν χρειάζεστε τον <code>arraylist&lt;namevaluepair&gt;</code> για τις παραμέτρους, αυτή είναι μια συντομότερη λύση που δημιουργεί τη συμβολοσειρά επερωτήσεων χρησιμοποιώντας την κλάση <code>uri.builder</code>:</p><pre><code>url url = new url("http://yoururl.com"); httpsurlconnection conn = (httpsurlconnection) url.openconnection(); conn.setreadtimeout(10000); conn.setconnecttimeout(15000); conn.setrequestmethod("post"); conn.setdoinput(true); conn.setdooutput(true); uri.builder builder = new uri.builder() .appendqueryparameter("firstparam", paramvalue1) .appendqueryparameter("secondparam", paramvalue2) .appendqueryparameter("thirdparam", paramvalue3); string query = builder.build().getencodedquery(); outputstream os = conn.getoutputstream(); bufferedwriter writer = new bufferedwriter( new outputstreamwriter(os, "utf-8")); writer.write(query); writer.flush(); writer.close(); os.close(); conn.connect(); </code></pre>
<p>μια λύση είναι να φτιάξετε τη δική σας συμβολοσειρά παραστάσεων.</p><p>αυτή είναι η πραγματική μέθοδος που χρησιμοποιώ για το τελευταίο μου έργο. θα πρέπει να αλλάξετε args από hashtable σε namesvaluepair:</p><pre><code>private static string getpostparamstring(hashtable&lt;string, string&gt; params) { if(params.size() == 0) return ""; stringbuffer buf = new stringbuffer(); enumeration&lt;string&gt; keys = params.keys(); while(keys.hasmoreelements()) { buf.append(buf.length() == 0 ? "" : "&amp;"); string key = keys.nextelement(); buf.append(key).append("=").append(params.get(key)); } return buf.tostring(); } </code></pre><p>μεταφυση των παρασυμμάτων:</p><pre><code>outputstreamwriter writer = new outputstreamwriter(conn.getoutputstream()); writer.write(getpostparamstring(req.getpostparams())); </code></pre>
<p>νομίζω ότι βρήκα ακριβώς αυτό που χρειάζεστε. μπορεί να βοηθήσει άλλους.</p><p>μπορείτε να χρησιμοποιήσετε τη μέθοδο <em>rlencodedformentity.writeto (outputstream)</em>.</p><pre><code>urlencodedformentity formentity = new urlencodedformentity(nvp); http.connect(); outputstream output = null; try { output = http.getoutputstream(); formentity.writeto(output); } finally { if (output != null) try { output.close(); } catch (ioexception ioe) {} } </code></pre>
<p>η αποδεκτή απάντηση ρίχνει ένα protocolexception στη διεύθυνση:</p><p><code>outputstream os = conn.getoutputstream();</code></p><p>επειδή δεν επιτρέπει την έξοδο για το αντικείμενο urlconnection. η λύση θα πρέπει να περιλαμβάνει αυτό:</p><p><code>conn.setdooutput(true);</code></p><p>για να λειτουργήσει.</p>
<p>αν δεν είναι πολύ αργά, θα ήθελα να μοιραστώ τον κωδικό μου</p><p><strong>tils.java:</strong></p><pre><code>public static string buildpostparameters(object content) { string output = null; if ((content instanceof string) || (content instanceof jsonobject) || (content instanceof jsonarray)) { output = content.tostring(); } else if (content instanceof map) { uri.builder builder = new uri.builder(); hashmap hashmap = (hashmap) content; if (hashmap != null) { iterator entries = hashmap.entryset().iterator(); while (entries.hasnext()) { map.entry entry = (map.entry) entries.next(); builder.appendqueryparameter(entry.getkey().tostring(), entry.getvalue().tostring()); entries.remove(); // avoids a concurrentmodificationexception } output = builder.build().getencodedquery(); } } return output; } public static urlconnection makerequest(string method, string apiaddress, string accesstoken, string mimetype, string requestbody) throws ioexception { url url = new url(apiaddress); httpurlconnection urlconnection = (httpurlconnection) url.openconnection(); urlconnection.setdoinput(true); urlconnection.setdooutput(!method.equals("get")); urlconnection.setrequestmethod(method); urlconnection.setrequestproperty("authorization", "bearer " + accesstoken); urlconnection.setrequestproperty("content-type", mimetype); outputstream outputstream = new bufferedoutputstream(urlconnection.getoutputstream()); bufferedwriter writer = new bufferedwriter(new outputstreamwriter(outputstream, "utf-8")); writer.write(requestbody); writer.flush(); writer.close(); outputstream.close(); urlconnection.connect(); return urlconnection; } </code></pre><p><strong>mainactivity.java:</strong></p><pre><code>@override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity\_main); new apirequest().execute(); } private class apirequest extends asynctask&lt;void, void, string&gt; { @override protected object doinbackground(void... params) { // of course, you should comment the other cases when testing one case // case 1: for frombody parameter string url = "http://10.0.2.2/api/frombody"; string requestbody = utils.buildpostparameters("'frombody value'"); // must have '' for frombody parameter httpurlconnection urlconnection = null; try { urlconnection = (httpurlconnection) utils.makerequest("post", url, null, "application/json", requestbody); inputstream inputstream; // get stream if (urlconnection.getresponsecode() &lt; httpurlconnection.http\_bad\_request) { inputstream = urlconnection.getinputstream(); } else { inputstream = urlconnection.geterrorstream(); } // parse stream bufferedreader bufferedreader = new bufferedreader(new inputstreamreader(inputstream)); string temp, response = ""; while ((temp = bufferedreader.readline()) != null) { response += temp; } return response; } catch (ioexception e) { e.printstacktrace(); return e.tostring(); } finally { if (urlconnection != null) { urlconnection.disconnect(); } } // case 2: for jsonobject parameter string url = "http://10.0.2.2/api/testjsonobject"; jsonobject jsonbody; string requestbody; httpurlconnection urlconnection; try { jsonbody = new jsonobject(); jsonbody.put("title", "bnk title"); jsonbody.put("author", "bnk"); jsonbody.put("date", "2015/08/08"); requestbody = utils.buildpostparameters(jsonbody); urlconnection = (httpurlconnection) utils.makerequest("post", url, null, "application/json", requestbody); ... // the same logic to case #1 ... return response; } catch (jsonexception | ioexception e) { e.printstacktrace(); return e.tostring(); } finally { if (urlconnection != null) { urlconnection.disconnect(); } } // case 3: for form-urlencoded parameter string url = "http://10.0.2.2/api/token"; httpurlconnection urlconnection; map&lt;string, string&gt; stringmap = new hashmap&lt;&gt;(); stringmap.put("grant\_type", "password"); stringmap.put("username", "username"); stringmap.put("password", "password"); string requestbody = utils.buildpostparameters(stringmap); try { urlconnection = (httpurlconnection) utils.makerequest("post", url, null, "application/x-www-form-urlencoded", requestbody); ... // the same logic to case #1 ... return response; } catch (exception e) { e.printstacktrace(); return e.tostring(); } finally { if (urlconnection != null) { urlconnection.disconnect(); } } } @override protected void onpostexecute(string response) { super.onpostexecute(response); // do something... } } </code></pre>
<p>υπάρχει πολύ πιο εύκολη προσέγγιση χρησιμοποιώντας τον printwriter (δείτε <a href="https://ihofmann.wordpress.com/2013/01/23/android-sending-post-requests-with-parameters/">εδώ</a> )</p><p>βασικά το μόνο που χρειάζεστε είναι:</p><pre><code>// set up url connection url urltorequest = new url(urlstr); httpurlconnection urlconnection = (httpurlconnection)urltorequest.openconnection(); urlconnection.setdooutput(true); urlconnection.setrequestmethod("post"); urlconnection.setrequestproperty("content-type", "application/x-www-form-urlencoded"); // write out form parameters string postparamaters = "param1=value1&amp;param2=value2" urlconnection.setfixedlengthstreamingmode(postparameters.getbytes().length); printwriter out = new printwriter(urlconnection.getoutputstream()); out.print(postparameters); out.close(); // connect urlconnection.connect(); </code></pre>
<p><code>asynctask</code> για την αποστολή δεδομένων ως <code>jsonobect</code> μέσω <code>post</code> μέθοδος</p><pre><code>public class postmethoddemo extends asynctask&lt;string , void ,string&gt; { string server\_response; @override protected string doinbackground(string... strings) { url url; httpurlconnection urlconnection = null; try { url = new url(strings[0]); urlconnection = (httpurlconnection) url.openconnection(); urlconnection.setdooutput(true); urlconnection.setdoinput(true); urlconnection.setrequestmethod("post"); dataoutputstream wr = new dataoutputstream(urlconnection.getoutputstream ()); try { jsonobject obj = new jsonobject(); obj.put("key1" , "value1"); obj.put("key2" , "value2"); wr.writebytes(obj.tostring()); log.e("json input", obj.tostring()); wr.flush(); wr.close(); } catch (jsonexception ex) { ex.printstacktrace(); } urlconnection.connect(); int responsecode = urlconnection.getresponsecode(); if(responsecode == httpurlconnection.http\_ok){ server\_response = readstream(urlconnection.getinputstream()); } } catch (malformedurlexception e) { e.printstacktrace(); } catch (ioexception e) { e.printstacktrace(); } return null; } @override protected void onpostexecute(string s) { super.onpostexecute(s); log.e("response", "" + server\_response); } } public static string readstream(inputstream in) { bufferedreader reader = null; stringbuffer response = new stringbuffer(); try { reader = new bufferedreader(new inputstreamreader(in)); string line = ""; while ((line = reader.readline()) != null) { response.append(line); } } catch (ioexception e) { e.printstacktrace(); } finally { if (reader != null) { try { reader.close(); } catch (ioexception e) { e.printstacktrace(); } } } return response.tostring(); } </code></pre>
<p>δοκιμάστε αυτό:</p><pre><code>httpclient httpclient = new defaulthttpclient(); httppost httppost = new httppost("your url"); list&lt;namevaluepair&gt; namevaluepairs = new arraylist&lt;namevaluepair&gt;(3); namevaluepairs.add(new basicnamevaluepair("user\_name", "name")); namevaluepairs.add(new basicnamevaluepair("pass","password" )); namevaluepairs.add(new basicnamevaluepair("user\_email","email" )); httppost.setentity(new urlencodedformentity(namevaluepairs)); // execute http post request httpresponse response = httpclient.execute(httppost); string ret = entityutils.tostring(response.getentity()); log.v("util response", ret); </code></pre><p>μπορείτε να προσθέσετε όσες <code>namevaluepairs</code> όπως χρειάζεστε. και μην ξεχάσετε να αναφέρετε τον αριθμό στον κατάλογο.</p>
<p>για να καλέσετε post/put/delete/get μέθοδοι restless με custom header ή json δεδομένα μπορεί να χρησιμοποιηθεί η ακόλουθη κλάση async</p><pre><code>public class httpurlconnectionutlity extends asynctask&lt;integer, void, string&gt; { private static final string tag = "httpurlconnectionutlity"; context mcontext; public static final int get\_method = 0, post\_method = 1, put\_method = 2, head\_method = 3, delete\_method = 4, trace\_method = 5, options\_method = 6; hashmap&lt;string, string&gt; headermap; string entitystring; string url; int requesttype = -1; final string timeout = "timed\_out"; int time\_out = 60 * 1000; public httpurlconnectionutlity (context mcontext) { this.mcontext = mcontext; this.callback = callback; } @override protected void onpreexecute() { super.onpreexecute(); } @override protected string doinbackground(integer... params) { int requesttype = getrequesttype(); string response = ""; try { url url = geturl(); httpurlconnection urlconnection = (httpurlconnection) url.openconnection(); urlconnection = setrequestmethod(urlconnection, requesttype); urlconnection.setconnecttimeout(time\_out); urlconnection.setreadtimeout(time\_out); urlconnection.setdooutput(true); urlconnection = setheaderdata(urlconnection); urlconnection = setentity(urlconnection); if (urlconnection.getresponsecode() == httpurlconnection.http\_ok) { response = readresponsestream(urlconnection.getinputstream()); logger.v(tag, response); } urlconnection.disconnect(); return response; } catch (protocolexception e) { e.printstacktrace(); } catch (sockettimeoutexception e) { return timeout; } catch (ioexception e) { e.printstacktrace(); } catch (illegalstateexception e) { logger.e(tag, "already connected"); } return response; } @override protected void onpostexecute(string response) { super.onpostexecute(response); if (textutils.isempty(response)) { //empty response } else if (response != null &amp;&amp; response.equals(timeout)) { //request timed out } else { //process your response } } private string getentitystring() { return entitystring; } public void setentitystring(string s) { this.entitystring = s; } private string readresponsestream(inputstream in) { bufferedreader reader = null; stringbuffer response = new stringbuffer(); try { reader = new bufferedreader(new inputstreamreader(in)); string line = ""; while ((line = reader.readline()) != null) { response.append(line); } } catch (ioexception e) { e.printstacktrace(); } finally { if (reader != null) { try { reader.close(); } catch (ioexception e) { e.printstacktrace(); } } } return response.tostring(); } private httpurlconnection setentity(httpurlconnection urlconnection) throws ioexception { if (getentitystring() != null) { outputstream outputstream = urlconnection.getoutputstream(); bufferedwriter writer = new bufferedwriter(new outputstreamwriter(outputstream, "utf-8")); writer.write(getentitystring()); writer.flush(); writer.close(); outputstream.close(); } else { logger.w(tag, "no entity data to append ||no entity data to append ||no entity data to append"); } return urlconnection; } private httpurlconnection setheaderdata(httpurlconnection urlconnection) throws unsupportedencodingexception { urlconnection.setrequestproperty("content-type", "application/json"); urlconnection.setrequestproperty("accept", "application/json"); if (getheadermap() != null) { for (map.entry&lt;string, string&gt; entry : getheadermap().entryset()) { urlconnection.setrequestproperty(entry.getkey(), entry.getvalue()); } } else { logger.w(tag, "no header data to append ||no header data to append ||no header data to append"); } return urlconnection; } private httpurlconnection setrequestmethod(httpurlconnection urlconnection, int requestmethod) { try { switch (requestmethod) { case get\_method: urlconnection.setrequestmethod("get"); break; case post\_method: urlconnection.setrequestmethod("post"); break; case put\_method: urlconnection.setrequestmethod("put"); break; case delete\_method: urlconnection.setrequestmethod("delete"); break; case options\_method: urlconnection.setrequestmethod("options"); break; case head\_method: urlconnection.setrequestmethod("head"); break; case trace\_method: urlconnection.setrequestmethod("trace"); break; } } catch (protocolexception e) { e.printstacktrace(); } return urlconnection; } public int getrequesttype() { return requesttype; } public void setrequesttype(int requesttype) { this.requesttype = requesttype; } public url geturl() throws malformedurlexception { return new url(url); } public void seturl(string url) { this.url = url; } public hashmap&lt;string, string&gt; getheadermap() { return headermap; } public void setheadermap(hashmap&lt;string, string&gt; headermap) { this.headermap = headermap; } } </code></pre><p>και η χρήση είναι</p><pre><code> httpurlconnectionutlity httpmethod = new httpurlconnectionutlity (mcontext); jsonobject jsonentity = new jsonobject(); try { jsonentity.put("key1", value1); jsonentity.put("key2", value2); } catch (jsonexception e) { e.printstacktrace(); } httpmethod.seturl(your\_url\_string); hashmap&lt;string, string&gt; headermap = new hashmap&lt;&gt;(); headermap.put("key",value); headermap.put("key1",value1); httpmethod.setheadermap(headermap); httpmethod.setrequesttype(wiseconnecthttpmethod.post\_method); //specify post/get/delete/put httpmethod.setentitystring(jsonentity.tostring()); httpmethod.execute(); </code></pre>
<p>χρησιμοποιώντας org.apache.http.client.httpclient επίσης μπορείτε να το κάνετε εύκολα με πιο ευανάγνωστο τρόπο όπως παρακάτω.</p><pre><code>httpclient httpclient = new defaulthttpclient(); httppost httppost = new httppost("http://www.yoursite.com/script.php"); </code></pre><p>εντός της δοκιμαστικής αλίευσης μπορείτε να εισάγετε</p><pre><code>// add your data list&lt;namevaluepair&gt; namevaluepairs = new arraylist&lt;namevaluepair&gt;(2); namevaluepairs.add(new basicnamevaluepair("id", "12345")); namevaluepairs.add(new basicnamevaluepair("stringdata", "anddev is cool!")); httppost.setentity(new urlencodedformentity(namevaluepairs)); // execute http post request httpresponse response = httpclient.execute(httppost); </code></pre>
<p>χρησιμοποιώ κάτι τέτοιο:</p><pre><code>schemeregistry sr = new schemeregistry(); sr.register(new scheme("https", sslsocketfactory.getsocketfactory(), 443)); httpparams params = new basichttpparams(); singleclientconnmanager mgr = new singleclientconnmanager(params, sr); httpclient httpclient = new defaulthttpclient(mgr, params); httppost httppost = new httppost(url); httppost.setentity(new urlencodedformentity(namevaluepairs)); httpresponse response = httpclient.execute(httppost); </code></pre>
<p>στην περίπτωσή μου, δημιούργησα μια λειτουργία όπως αυτή για να δημιουργήσω ένα post request το οποίο παίρνει τη διεύθυνση url string και hashmap των παραμέτρων</p><pre><code> public string postrequest( string mainurl,hashmap&lt;string,string&gt; parameterlist) { string response=""; try { url url = new url(mainurl); stringbuilder postdata = new stringbuilder(); for (map.entry&lt;string, string&gt; param : parameterlist.entryset()) { if (postdata.length() != 0) postdata.append('&amp;'); postdata.append(urlencoder.encode(param.getkey(), "utf-8")); postdata.append('='); postdata.append(urlencoder.encode(string.valueof(param.getvalue()), "utf-8")); } byte[] postdatabytes = postdata.tostring().getbytes("utf-8"); httpurlconnection conn = (httpurlconnection) url.openconnection(); conn.setrequestmethod("post"); conn.setrequestproperty("content-type", "application/x-www-form-urlencoded"); conn.setrequestproperty("content-length", string.valueof(postdatabytes.length)); conn.setdooutput(true); conn.getoutputstream().write(postdatabytes); reader in = new bufferedreader(new inputstreamreader(conn.getinputstream(), "utf-8")); stringbuilder sb = new stringbuilder(); for (int c; (c = in.read()) &gt;= 0; ) sb.append((char) c); response = sb.tostring(); return response; }catch (exception excep){ excep.printstacktrace();} return response; } </code></pre>