httpUrlConnection连接网络的用法(用到了handle传递消息,在主线程中更新UI)
由于httpclient在Android5.0以后已经过时,所以官方推荐使用httpUrlConnection来连接网络,现将该连接的基本方法展示,如下



注意:记得加入<uses-permission android:name="android.permission.INTERNET" />
另外,本例用到了handle来处理消息,跟新UI在主线程中,访问网络在子线程中
客户端代码:
package imqsl.com.testhttp; import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast; import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder; public class MainActivity extends AppCompatActivity {
Button button = null;
EditText edit = null;
TextView textView = null;
String result="";
Handler handler=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button= (Button) findViewById(R.id.button);
edit= (EditText) findViewById(R.id.edit);
textView= (TextView) findViewById(R.id.text_display);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if ("".equals(edit.getText().toString())){
Toast.makeText(MainActivity.this,"请输入要发送的内容",Toast.LENGTH_SHORT).show();
return;
}
new Thread(new Runnable() {
@Override
public void run() {
send();
Message msg=handler.obtainMessage();//子线程中的handle用来给主线程传递消息,虽然本例中的msg没有使用,
但是主线程中的handle也要等待该Message,否则不会继续,然后更新UI
handler.sendMessage(msg);
}
}).start();
}
});
handler=new Handler(){//主线程中的handle用来接收子线程中的Message以便更新UI
@Override
public void handleMessage(Message msg) {
Toast.makeText(MainActivity.this,result,Toast.LENGTH_SHORT).show();
if (result!=null){
textView.setText(result);
edit.setText("");
}
super.handleMessage(msg);
}
}; } private void send() {
URL url;
String target = "http://192.168.1.152:8080/flightcheck/testservlet";
try {
url=new URL(target);
HttpURLConnection urlConn= (HttpURLConnection) url.openConnection();//注意:httpURLconnetion的创建是这样自的
urlConn.setRequestMethod("POST");//设置连接方式,post必须设置,get可以不用设置,因为默认的就是get
urlConn.setUseCaches(false);//是指是否缓存
urlConn.setDoInput(true);//设置是否输入
urlConn.setDoOutput(true);//设置是否输出
DataOutputStream out=new DataOutputStream(urlConn.getOutputStream());
String param="content="+ URLEncoder.encode(edit.getText().toString(),"utf-8");//使用URLEncoder.encode转换为utf-8以防止中文乱码
out.writeBytes(param);//writeBytes写字节到输出流中,服务器端也是接收的bytes
out.flush();//记得刷一下
out.close();
System.out.println("responsecode:"+urlConn.getResponseCode());
if (urlConn.getResponseCode()==HttpURLConnection.HTTP_OK){//连接成功,则相等,httpURLConnection.http_ok=200
BufferedReader bufferedReader=new BufferedReader(new //处理流,转换流,节点流
InputStreamReader(urlConn.getInputStream()));
String line=null;
System.out.println("bufferedReader.readLine():"+bufferedReader.readLine());
while ((line=bufferedReader.readLine())!=null){
result+=line+"\n"; //加了个"\n"相当于换到了下一行
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} }
}
xml文件代码:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/edit"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="发表"
android:id="@+id/button"
/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/text_display"
/> </LinearLayout>
服务器端代码:
package test; import java.io.IOException;
import java.io.PrintWriter; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class testservlet extends HttpServlet {
private static final long serialVersionUID = 1L; public testservlet() {
super();
} protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String content = new String(request.getParameter("content").getBytes("ISO-8859-1"), "UTF-8");//客户端writeBytes,服务器端就getBytes并转码
System.out.println(content);
response.setContentType("text/plain");
response.setCharacterEncoding("utf-8");//加入本步设置客户端就可以得到服务器端发来的正确的中文了 PrintWriter out=response.getWriter();//打印流,输出流,向客户端输入的意思
out.print(content);//输出流,向客户端输入的意思
out.flush();//打印流记得刷一下,不然不行
out.close();
} protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
} }
httpUrlConnection连接网络的用法(用到了handle传递消息,在主线程中更新UI)的更多相关文章
- android4.0以上访问网络不能在主线程中进行以及在线程中操作UI的解决方法
MONO 调用一个线程操作UI 然后报Only the original thread that created a view hierarchy can touch its views.错误 goo ...
- Android之Handler用法总结/安卓中只有主线程可以修改UI
Handler传递消息的方式可以实现实时刷新以及长按连续响应事件. 按钮响应 btnadd_fcl.setOnTouchListener(new View.OnTouchListener() { pr ...
- 安卓中使用HttpURLConnection连接网络简单示例 --Android网络编程
MainActivity.java: package thonlon.example.cn.httpurlconnectionpro; import android.os.Bundle;import ...
- android4.0 HttpClient 以后不能在主线程发起网络请求
android4.0以后不能在主线程发起网络请求,该异步网络请求. new Thread(new Runnable() { @Override public void run() { // TODO ...
- android——网络操作(一)连接网络
连接网络 一,包含许可 <uses-permissionandroid:name="android.permission.INTERNET"/> <uses-pe ...
- android.os.NetworkOnMainThreadException 在4.0之后谷歌强制要求连接网络不能在主线程进行访问
谷歌在4.0系统以后就禁止在主线程中进行网络访问了,原因是: 主线程是负责UI的响应,如果在主线程进行网络访问,超过5秒的话就会引发强制关闭, 所以这种耗时的操作不能放在主线程里.放在子线程里,而子线 ...
- HttpURLConnection请求网络数据的GET请求
//清单文件中添加权限 <uses-permission android:name="android.permission.INTERNET"/> new Thread ...
- Android热身:通过网络获取资源并更新UI组件
Android热身:通过网络获取资源并更新UI组件 目标 点击"发送请求"按钮,下载某网页的html源码,并显示在TextView控件上:点击"清空",清除Te ...
- Android主线程不能访问网络异常解决办法
从两个方面说下这个问题: 1. 不让访问网络的原因 2. 解决该问题的办法 不让访问网络的原因: 由于对于网络状况的不可预见性,很有可能在网络访问的时候造成阻塞,那么这样一来我们的主线程UI线程 就会 ...
随机推荐
- Struts2 引入
引入: 说:如果一个路径想访问一个类,需求怎么做? 第一种方法,用servlet 第二种方法,用过滤器 第三种方法如下图:把路径和方法都存到map里面,用反射可以执行类下的方法 第三中方法 ...
- c 数组作为返回值注意
static char* Test() { char buf[] ="aa"; printf("%s\n",buf); return buf; } int ma ...
- 免费证书申请——Let's Encrypt的申请与应用(IIS,Tomcat)
环境 Windows Server 2008 R2 Tomcat 8.5.31 JDK8 利用IIS+letsencrypt-win-simple.V1.9.1申请免费SSL证书 新建一个IIS空网站 ...
- javascript table排序之jquery.tablesorter.js
table排序 jquery.tablesorter.js 一.Demo下载地址: 1.tablesorter.js下载地址: http://download.csdn.net/detail/zhan ...
- C++时间操作的汇总
. 获取当前时间 time_t cur_time = time(NULL); . 把整数时间转为字符串时间 string GetStringTime(const time_t time) { stru ...
- Linux性能指标解释+Oracle性能指标解释
Linux性能指标解释 类别 计数器名称 计数器描述 业界同行认可的资源阀值 memory Free(KB) 可用物理内存数 swap-in/out =0 Swap(KB) 已使用的虚拟内存数.在Li ...
- ubuntu - 安装hive
粗略步骤: 详细参考:https://www.2cto.com/net/201804/735478.html 环境:ubunut jdk hadoop mysql 一.下载hive 二.解压( ...
- java中计算一段时间内白天的时间和夜晚的时间
之前,采用拼接字符串的形式,不断地在Date类型和Long类型之间转换,实在是太过于麻烦,后来采取了这种思路:假设我们将22:00 ~ 10:00 视为夜间时间,则我们先计算出10:00 相对于当天的 ...
- 循环队列(Joseplus Problem)
#include <iostream> #include <stdio.h> using namespace std; ]; ; void Enqueue(int x) { ) ...
- 我的iphone不能被虚拟机识别怎么办
我的iphone不能被虚拟机识别怎么办 听语音 | 浏览:3890 | 更新:2015-11-04 15:28 | 标签:iphone vmware ios 1 2 3 4 5 6 分步阅读 特大喜讯 ...