4种安卓自带的HTTP通讯方式(只是例子,网络通讯就随便写在主线)

public class Activity1 extends Activity {
  
    private final String DEBUG_TAG = "System.out";
  
    private TextView mTextView;
    private Button mButton;
  
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
  
        mTextView = (TextView) findViewById(R.id.TextView01);
        mButton = (Button) findViewById(R.id.Button01);
        mButton.setOnClickListener(new httpListener());
    }
  
    // 设置按钮监听器
    class httpListener implements OnClickListener {
        public void onClick(View v) {
            refresh();
        }
    }
  
    private void refresh() {
        String httpUrl = "http://192.168.0.101:8080/Test/test.jsp";
        // URL可以加参数
        // String httpUrl =
        // "http://192.168.0.101:8080/Test/test.jsp?par=abcdefg";
        String resultData = "";
        URL url = null;
        try {
            // 创建一个URL对象
            url = new URL(httpUrl);
        } catch (MalformedURLException e) {
            Log.d(DEBUG_TAG, "create URL Exception");
        }
        // 声明HttpURLConnection对象
        HttpURLConnection urlConn = null;
        // 声明InputStreamReader对象
        InputStreamReader in = null;
        // 声明BufferedReader对象
        BufferedReader buffer = null;
        String inputLine = null;
        if (url != null) {
            try {
                // 使用HttpURLConnection打开连接
                urlConn = (HttpURLConnection) url.openConnection();
                // 得到读取的内容(流)
                in = new InputStreamReader(urlConn.getInputStream());
                // 创建BufferReader对象,输出时候用到
                buffer = new BufferedReader(in);
                // 使用循环来读取数据
                while ((inputLine = buffer.readLine()) != null) {
                    // 在每一行后面加上换行
                    resultData += inputLine + "\n";
                }
                // 设置显示取的的内容
                if (resultData != null && !resultData.equals("")) {
                    mTextView.setText(resultData);
                } else {
                    mTextView.setText("读取的内容为空");
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    // 关闭InputStreamReader
                    in.close();
                    // 关闭URL连接
                    urlConn.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } else {
            Log.d(DEBUG_TAG, "URL is NULL");
        }
    }
}
第二种方式:

public class Activity2 extends Activity {
  
    private final String DEBUG_TAG = "System.out";
  
    private TextView mTextView;
    private Button mButton;
  
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
  
        mTextView = (TextView) findViewById(R.id.TextView01);
        mButton = (Button) findViewById(R.id.Button01);
        mButton.setOnClickListener(new httpListener());
    }
  
    // 设置按钮监听器
    class httpListener implements OnClickListener {
        public void onClick(View v) {
            refresh();
        }
    }
  
    private void refresh() {
        String httpUrl = "http://192.168.0.101:8080/Test/test.jsp";
        String resultData = "";
        URL url = null;
        try {
            // 创建一个URL对象
            url = new URL(httpUrl);
        } catch (MalformedURLException e) {
            Log.d(DEBUG_TAG, "create URL Exception");
        }
        // 声明HttpURLConnection对象
        HttpURLConnection urlConn = null;
        // 声明InputStreamReader对象
        InputStreamReader in = null;
        // 声明BufferedReader对象
        BufferedReader buffer = null;
        String inputLine = null;
        // 声明DataOutputStream流
        DataOutputStream out = null;
        if (url != null) {
            try {
                // 使用HttpURLConnection打开连接
                urlConn = (HttpURLConnection) url.openConnection();
                // 因为这个是POST请求所以要设置为true
                urlConn.setDoInput(true);
                urlConn.setDoOutput(true);
                // 设置POST方式
                urlConn.setRequestMethod("POST");
                // POST请求不能设置缓存
                urlConn.setUseCaches(false);
                urlConn.setInstanceFollowRedirects(false);
                // 配置本次连接的Content-type,配置为application/x-www-form-urlencoded的
                urlConn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
                // 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成
                // 要注意的是connectio.getOutputStream会隐含的进行connect
                urlConn.connect();
                // DataOutputStream流
                out = new DataOutputStream(urlConn.getOutputStream());
                String content = "par=" + URLEncoder.encode("abcdefg", "gb2312");
                // 将要上传的内容写入流中
                out.writeBytes(content);
                // 得到读取的内容(流)
                in = new InputStreamReader(urlConn.getInputStream());
                // 创建BufferReader对象,输出时候用到
                buffer = new BufferedReader(in);
                // 使用循环来读取数据
                while ((inputLine = buffer.readLine()) != null) {
                    // 在每一行后面加上换行
                    resultData += inputLine + "\n";
                }
                // 设置显示取的的内容
                if (resultData != null && !resultData.equals("")) {
                    mTextView.setText(resultData);
                } else {
                    mTextView.setText("读取的内容为空");
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    // 刷新DataOutputStream流
                    out.flush();
                    // 关闭DataOutputStream流
                    out.close();
                    // 关闭InputStreamReader
                    in.close();
                    // 关闭URL连接
                    urlConn.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } else {
            Log.d(DEBUG_TAG, "URL is NULL");
        }
    }
}
第三种方式

public class Activity3 extends Activity{
    private TextView mTextView;
    private Button mButton;
  
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mTextView = (TextView) findViewById(R.id.TextView01);
        mButton = (Button) findViewById(R.id.Button01);
        mButton.setOnClickListener(new httpListener());
    }
  
    // 设置按钮监听器
    class httpListener implements OnClickListener {
        public void onClick(View v) {
            String httpUrl = "http://192.168.0.101:8080/Test/test.jsp?par=HttpClient_android_Get";
            // HttpGet连接对象
            HttpGet httpRequest = new HttpGet(httpUrl);
            try {
                // 取的HttpClient对象
                HttpClient httpclient = new DefaultHttpClient();
                // 请求HttpClient,取的HttpResponse
                HttpResponse httpResponse = httpclient.execute(httpRequest);
                // 请求成功
                if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    // 取的返回的字符串
                    String strResult = EntityUtils.toString(httpResponse.getEntity());
                    // 这个返回值可能会在行尾出现小方格
                    // 在TextView要显示的文字过滤掉回车符("\r")就可以正常显示了。
                    String strsResult = strResult.replace("\r", "");
                    mTextView.setText(strsResult);
                } else {
                    mTextView.setText("请求错误");
                }
            } catch (ClientProtocolException e) {
                mTextView.setText(e.getMessage().toString());
            } catch (IOException e) {
                mTextView.setText(e.getMessage().toString());
            } catch (Exception e) {
                mTextView.setText(e.getMessage().toString());
            }
        }
    }
}
第四种方式

public class Activity4 extends Activity{
    private TextView mTextView;
    private Button mButton;
  
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mTextView = (TextView) findViewById(R.id.TextView01);
        mButton = (Button) findViewById(R.id.Button01);
        mButton.setOnClickListener(new httpListener());
    }
  
    // 设置按钮监听器
    class httpListener implements OnClickListener {
        public void onClick(View arg0) {
            String httpUrl = "http://192.168.0.101:8080/Test/test.jsp";
            // 创建HttpPost连接对象
            HttpPost httpRequest = new HttpPost(httpUrl);
            // 使用NameValuePair来保存要传递的Post参数
            List params = new ArrayList();
            // 添加要传递的参数
            params.add(new BasicNameValuePair("par","HttpClient_android_Post"));
            try {
                // 设置字符集
                HttpEntity httpentity = new UrlEncodedFormEntity(params,"gb2312");
                // 请求httpRequest
                httpRequest.setEntity(httpentity);
                // 取的默认的HttpClient
                HttpClient httpclient = new DefaultHttpClient();
                // 取的HttpResponse
                HttpResponse httpResponse = httpclient.execute(httpRequest);
                // HttpStatus.SC_OK表示连接成功
                if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    // 取的返回的字符串
                    String strResult = EntityUtils.toString(httpResponse.getEntity());
                    // 这个返回值可能会在行尾出现小方格
                    // 在TextView要显示的文字过滤掉回车符("\r")就可以正常显示了。
                    String strsResult = strResult.replace("\r", "");
                    mTextView.setText(strsResult);
                } else {
                    mTextView.setText("请求错误");
                }
            } catch (ClientProtocolException e) {
                mTextView.setText(e.getMessage().toString());
            } catch (IOException e) {
                mTextView.setText(e.getMessage().toString());
            } catch (Exception e) {
                mTextView.setText(e.getMessage().toString());
            }
        }
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
使用Basic4android实现Android的Socket通讯通信非常简单。首先,我们需要导入B4A Sockets库。在B4A的IDE中,点击“工具”菜单,然后选择“额外库管理器”,搜索并选择“B4A Sockets”,点击“添加到项目”。 接下来,我们需要创建一个活动或服务来处理Socket通讯。首先,在模块中添加以下代码以初始化Socket: ``` Sub Process_Globals Dim Socket1 As Socket End Sub Sub Activity_Create(FirstTime As Boolean) Socket1.Initialize("Socket1") Socket1.Connect("192.168.1.1", 1234, 5000) '连接到服务器 End Sub ``` 在上面的代码中,我们创建了一个名为Socket1的Socket对象,并在创建活动时初始化它。然后,我们使用Socket1.Connect方法连接到服务器的IP地址和端口号。 接下来,我们可以在发送按钮的单击事件中发送数据到服务器: ``` Sub Button1_Click Dim Out As OutputStream Out = Socket1.OutputStream Dim DataToSend() As Byte DataToSend = "Hello!".GetBytes("UTF8") '将字符串转换为字节数组 Out.WriteBytes(DataToSend) '发送数据 End Sub ``` 在上面的代码中,我们获取Socket的OutputStream对象,并将要发送的字符串转换为字节数组。然后,我们使用OutputStream的WriteBytes方法将字节数组发送到服务器。 最后,在Socket的Ready事件中接收来自服务器的数据: ``` Sub Socket1_Ready (Success As Boolean) If Success Then Dim In As InputStream In = Socket1.InputStream Dim Buffer(100) As Byte '定义一个缓冲区来接收数据 Dim BytesRead As Int BytesRead = In.ReadBytes(Buffer, 0, Buffer.Length) '从输入流中读取数据到缓冲区 Dim DataReceived As String DataReceived = BytesToString(Buffer, 0, BytesRead, "UTF8") '将字节数组转换为字符串 Log(DataReceived) '打印接收到的数据 Else Log("连接失败") End If End Sub ``` 在上面的代码中,我们获取Socket的InputStream对象,并通过InputStream的ReadBytes方法从输入流中读取数据到缓冲区。然后,我们将字节数组转换为字符串,并使用Log方法打印接收到的数据。 通过以上步骤,我们就实现了Basic4android中的Android Socket通讯通信。需要注意的是,在实际开发中,我们还需要处理异常情况和关闭Socket连接等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值