android 使用post方式进行网络连接

 private String connect(){
        String uri = ETwebAddress.getText().toString();
        StringBuilder sb =new StringBuilder();
        BufferedReader in = null;
        if("".equals(uri)){
            Toast.makeText(this,"empaty address",Toast.LENGTH_LONG).show();
        }else{
            HttpPost postRequest = new HttpPost(uri);
            ArrayList<NameValuePair> params = new ArrayList<>();//create name value pair arraylist
            params.add(new BasicNameValuePair("name","tom")); //add parameters to list
            params.add(new BasicNameValuePair("password","12345"));
            try{
            postRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));//set entity content in the post request
                HttpResponse response = new DefaultHttpClient().execute(postRequest);//get connection response
                if(response.getStatusLine().getStatusCode()== HttpStatus.SC_OK){
                    in = new BufferedReader(
                            new InputStreamReader(response.getEntity().getContent()));//get stream
                    String NL = System.getProperty("line.separator");
                    String line="";
                    sb = new StringBuilder();
                    while((line = in.readLine())!=null){
                        sb.append(line+NL);
                    }
                    in.close();
                }else{
                    sb.append("connection failure...");
                }
            }catch (Exception e){
                e.printStackTrace();
                Toast.makeText(this,"connection exception",Toast.LENGTH_LONG).show();
            }
        }
        return sb.toString();
    }

 

posted @ 2015-06-02 21:19  湖心北斗  阅读(341)  评论(0编辑  收藏  举报