Monkey2HttpRequest.java 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  1. package com.monkey2.lib;
  2. import android.util.Log;
  3. import java.io.ByteArrayOutputStream;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.io.OutputStream;
  7. import java.net.HttpURLConnection;
  8. import java.net.URL;
  9. public class Monkey2HttpRequest{
  10. private static final String TAG = "Monkey2HttpRequest";
  11. HttpURLConnection connection;
  12. int readyState;
  13. boolean busy;
  14. native void onNativeReadyStateChanged( int state );
  15. native void onNativeResponseReceived( String response,int status,int state );
  16. void setReadyState( int state ){
  17. if( state==readyState ) return;
  18. onNativeReadyStateChanged( state );
  19. readyState=state;
  20. }
  21. void open( String req,String url ){
  22. if( readyState!=0 ) return;
  23. try{
  24. URL turl=new URL( url );
  25. connection=(HttpURLConnection)turl.openConnection();
  26. connection.setRequestMethod( req );
  27. setReadyState( 1 );
  28. }catch( IOException ex ){
  29. setReadyState( 5 );
  30. }
  31. }
  32. void setHeader( String name,String value ){
  33. if( readyState!=1 || busy ) return;
  34. connection.setRequestProperty( name,value );
  35. }
  36. void send( final String text ){
  37. if( readyState!=1 || busy ) return;
  38. busy=true;
  39. new Thread( new Runnable() {
  40. public void run() {
  41. try {
  42. if( text!=null && text.length()!=0 ){
  43. byte[] bytes=text.getBytes( "UTF-8" );
  44. connection.setDoOutput( true );
  45. connection.setFixedLengthStreamingMode( bytes.length );
  46. OutputStream out=connection.getOutputStream();
  47. out.write( bytes,0,bytes.length );
  48. out.close();
  49. }
  50. InputStream in=connection.getInputStream();
  51. setReadyState( 3 );
  52. byte[] buf = new byte[4096];
  53. ByteArrayOutputStream out=new ByteArrayOutputStream(1024);
  54. for (; ; ) {
  55. int n = in.read(buf);
  56. if (n < 0) break;
  57. out.write(buf, 0, n);
  58. }
  59. in.close();
  60. String response=new String( out.toByteArray(),"UTF-8" );
  61. int status=connection.getResponseCode();
  62. onNativeResponseReceived( response,status,4 );
  63. readyState=4;
  64. } catch ( IOException ex) {
  65. setReadyState( 5 );
  66. }
  67. busy=false;
  68. }
  69. } ).start();
  70. }
  71. }