Android URLconnection

使用Thread请求HTTP

普通的使用java的Thread 线程,在重写run 方法,实现HTTPConnection

public class DoubleMeActivity extends Activity implements OnClickListener {

    EditText inputValue=null;
    Integer doubledValue =0;
    Button doubleMe;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.calculate);

        inputValue = (EditText) findViewById(R.id.inputNum);
        doubleMe = (Button) findViewById(R.id.doubleme);

        doubleMe.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()){
        case R.id.doubleme:

              new Thread(new Runnable() {
                    public void run() {

                        try{
                            URL url = new URL("http://10.0.2.2:8080/MyServletProject/DoubleMeServlet");
                            URLConnection connection = url.openConnection();

                            String inputString = inputValue.getText().toString();
                            //inputString = URLEncoder.encode(inputString, "UTF-8");

                            Log.d("inputString", inputString);

                            connection.setDoOutput(true);
                            OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
                            out.write(inputString);
                            out.close();

                            BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

                            String returnString="";
                            doubledValue =0;

                            while ((returnString = in.readLine()) != null) 
                            {
                                doubledValue= Integer.parseInt(returnString);
                            }
                            in.close();


                            runOnUiThread(new Runnable() {
                                 public void run() {

                                     inputValue.setText(doubledValue.toString());

                                }
                            });

                            }catch(Exception e)
                            {
                                Log.d("Exception",e.toString());
                            }

                    }
                  }).start();

            break;
            }
        }

    }

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。