访问服务器请求数据

来源:互联网 发布:阿里巴巴一件代发淘宝 编辑:程序博客网 时间:2024/05/21 17:53

布局文件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context="${relativePackage}.${activityClass}" >    <ScrollView        android:layout_width="match_parent"        android:layout_height="wrap_content"         >    <TextView        android:id="@+id/tv"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="@string/hello_world" /></ScrollView>    <Button        android:id="@+id/button1"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_alignParentTop="true"        android:layout_centerHorizontal="true"        android:text="Button" /></RelativeLayout>

java 文件:

public class MainActivity extends Activity {    private Button button;    private TextView tv;    private int SUCCESS = 1;    private Handler mHandler = new Handler() {        public void handleMessage(Message msg) {            tv.setText((CharSequence) msg.obj);        };    };    private int FAILE = 2;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        button = (Button) findViewById(R.id.button1);        tv = (TextView) findViewById(R.id.tv);        button.setOnClickListener(new OnClickListener() {            @Override            public void onClick(View v) {                final String bw1 = "http://192.168.191.1:8080/MyWebService/services/MyService";                new Thread(new Runnable() {                    @Override                    public void run() {                        try {                            InputStream isInputStream = sendSms(bw1,                                    "getBloodSend.xml");                            // 对获取到的输入流进行读取                            BufferedReader reader = new BufferedReader(                                    new InputStreamReader(isInputStream));                            String response = "", line;                            while ((line = reader.readLine()) != null) {                                response += line;                            }                            // 获取成功,发送成功信息                            Message message = new Message();                            message.what = SUCCESS;                            message.obj = response;                            mHandler.sendMessage(message);                        } catch (Exception e1) {                            e1.printStackTrace();                        }                    }                }).start();            }        });    }    public byte[] readInputStream(InputStream inStream) throws Exception {        ByteArrayOutputStream outStream = new ByteArrayOutputStream();        byte[] buffer = new byte[1024];        int len = 0;        while ((len = inStream.read(buffer)) != -1) {            outStream.write(buffer, 0, len);        }        byte[] data = outStream.toByteArray();// 网页的二进制数据        outStream.close();        inStream.close();        return data;    }    public InputStream sendSms(String webUrlRoot_webName, String fileName)            throws Exception {        try {            System.out.println(webUrlRoot_webName);            System.out.println(fileName);        } catch (Exception e) {        }        InputStream isInputStream = this.getResources().getAssets()                .open(fileName);//      String xml = readBufferedReader(isInputStream);//      Log.i("TAG", "xml====" + xml);//      xml = xml.replace("pdaCodetemp", "2154");//      isInputStream = new ByteArrayInputStream(xml.getBytes());        byte[] buf = readInputStream(isInputStream);        String soapActionString = "http://cdstm.org/";        URL url = new URL(webUrlRoot_webName);        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();        httpConn.setRequestProperty("Content-Length",                String.valueOf(buf.length));        httpConn.setRequestProperty("Content-Type", "text/xml; charset=utf-8");        httpConn.setRequestMethod("POST");        httpConn.setDoOutput(true);        httpConn.setDoInput(true);        httpConn.setConnectTimeout(5000);        OutputStream out = httpConn.getOutputStream();        out.write(buf);        out.close();        long date2 = System.currentTimeMillis();        InputStream is = httpConn.getInputStream();        return is;    }//  /**//   * 从输入流中读取数据//   * //   * @param inStream//   * @return//   * @throws Exception//   *///  public String readBufferedReader(InputStream inStream) throws Exception {//      BufferedReader reader = new BufferedReader(new InputStreamReader(//              inStream));//      StringBuffer buffer = new StringBuffer();//      String line = "";//      while ((line = reader.readLine()) != null) {//          buffer.append(line);//      }//      String xml = buffer.toString();//      return xml;//  }}

getBloodSend.xml

<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">  <soap:Body>    <example xmlns="http://WebXml.com.cn/">      <message>pdaCodetemp</message>    </example>  </soap:Body></soap:Envelope>