post data to script for Android 3.0


/ Published in: Java
Save to your folder(s)



Copy this code and paste it in your HTML
  1. //post data to script
  2. //be sure to declare private String response = ""; in declaration
  3. public String performPost(final String encodedData, final String theURL){
  4. Thread performPostThread = new Thread(new Runnable() {
  5.  
  6. @Override
  7. public void run() {
  8.  
  9. HttpURLConnection urlc = null;
  10. OutputStreamWriter out = null;
  11. DataOutputStream dataout = null;
  12. BufferedReader in = null;
  13. try {
  14. BT_debugger.showIt(fragmentName + ": posting to:" + theURL);
  15. BT_debugger.showIt(fragmentName + ": data: " + encodedData);
  16. URL url = new URL(theURL);
  17. urlc = (HttpURLConnection) url.openConnection();
  18. urlc.setRequestMethod("POST");
  19. urlc.setDoOutput(true);
  20. urlc.setDoInput(true);
  21. urlc.setUseCaches(false);
  22. urlc.setAllowUserInteraction(false);
  23. // urlc.setRequestProperty(HEADER_USER_AGENT, HEADER_USER_AGENT_VALUE);
  24. urlc.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
  25. dataout = new DataOutputStream(urlc.getOutputStream());
  26. // perform POST operation
  27. dataout.writeBytes(encodedData);
  28. in = new BufferedReader(new InputStreamReader(urlc.getInputStream()),8096);
  29.  
  30. // write html to System.out for debug
  31. StringBuilder sb = new StringBuilder();
  32. String line = null;
  33. BT_debugger.showIt(fragmentName + ": the response=");
  34. while ((line = in.readLine()) != null) {
  35. BT_debugger.showIt(line);
  36. sb.append(line + "\n");
  37. //return response;
  38.  
  39. }
  40. response = sb.toString();
  41. in.close();
  42. //return response;
  43. } catch (ProtocolException e) {
  44. response = e.toString();
  45. //return e.toString();
  46. } catch (IOException e) {
  47. response = e.toString();
  48. //return e.toString();
  49. } finally {
  50. if (out != null) {
  51. try {
  52. out.close();
  53. //return response;
  54. } catch (IOException e) {
  55. response = e.toString();
  56. //return e.toString();
  57. }
  58. }
  59. if (in != null) {
  60. try {
  61. in.close();
  62. } catch (IOException e) {
  63. //e.printStackTrace();
  64. response = e.toString();
  65. }
  66. }
  67. }
  68. }
  69. });
  70.  
  71. performPostThread.start();
  72.  
  73. try {
  74. performPostThread.join();
  75. } catch (InterruptedException e) {
  76. e.printStackTrace();
  77. }
  78.  
  79. return response;
  80.  
  81.  
  82.  
  83.  
  84. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.