由于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)的更多相关文章

  1. android4.0以上访问网络不能在主线程中进行以及在线程中操作UI的解决方法

    MONO 调用一个线程操作UI 然后报Only the original thread that created a view hierarchy can touch its views.错误 goo ...

  2. Android之Handler用法总结/安卓中只有主线程可以修改UI

    Handler传递消息的方式可以实现实时刷新以及长按连续响应事件. 按钮响应 btnadd_fcl.setOnTouchListener(new View.OnTouchListener() { pr ...

  3. 安卓中使用HttpURLConnection连接网络简单示例 --Android网络编程

    MainActivity.java: package thonlon.example.cn.httpurlconnectionpro; import android.os.Bundle;import ...

  4. android4.0 HttpClient 以后不能在主线程发起网络请求

    android4.0以后不能在主线程发起网络请求,该异步网络请求. new Thread(new Runnable() { @Override public void run() { // TODO ...

  5. android——网络操作(一)连接网络

    连接网络 一,包含许可 <uses-permissionandroid:name="android.permission.INTERNET"/> <uses-pe ...

  6. android.os.NetworkOnMainThreadException 在4.0之后谷歌强制要求连接网络不能在主线程进行访问

    谷歌在4.0系统以后就禁止在主线程中进行网络访问了,原因是: 主线程是负责UI的响应,如果在主线程进行网络访问,超过5秒的话就会引发强制关闭, 所以这种耗时的操作不能放在主线程里.放在子线程里,而子线 ...

  7. HttpURLConnection请求网络数据的GET请求

    //清单文件中添加权限 <uses-permission android:name="android.permission.INTERNET"/> new Thread ...

  8. Android热身:通过网络获取资源并更新UI组件

    Android热身:通过网络获取资源并更新UI组件 目标 点击"发送请求"按钮,下载某网页的html源码,并显示在TextView控件上:点击"清空",清除Te ...

  9. Android主线程不能访问网络异常解决办法

    从两个方面说下这个问题: 1. 不让访问网络的原因 2. 解决该问题的办法 不让访问网络的原因: 由于对于网络状况的不可预见性,很有可能在网络访问的时候造成阻塞,那么这样一来我们的主线程UI线程 就会 ...

随机推荐

  1. php数据连接

    <?php header("Content-type: text/html;charset=utf-8");//设置编码格式为UTF-8 error_reporting(E_ ...

  2. 2019年第十届蓝桥杯省赛总结(JavaA组)

    //update3.28:省一rank4,莫名进了国赛好神奇.. 记yzm10第一次体验A组(纯粹瞎水). 早闻山东的JavaA组神仙打架,进国赛都成了奢望(往年只有五个名额),因此抱着做分母的心态来 ...

  3. jQuery+css实现tab功能

    点击我我会消失 Click me 点击按钮我会消失,再点击我会出现 演示tab tab1 tab2 tab3 [环球时报记者 郭芳] “中国秘密发射新快速响应火箭”,25日,在中国官方媒体报道我国“快 ...

  4. MVVM模式下WPF动态绑定展示图片

    MVVM模式下WPF动态展示图片,界面选择图标,复制到项目中固定目录下面,保存到数据库的是相对路径,再次读取的时候是根据数据库的相对路径去获取项目中绝对路径的图片展示. 首先在ViewModel中 / ...

  5. javascript 常用兼容fire fox的解决办法

    常用兼容fire fox的解决办法 一.js不兼容:1.event不兼容,必须通过参数传递过来: function test(event){ //兼容fire fox var event = even ...

  6. 100个大型机器学习数据集汇总(CV/NLP/音频方向)

    网站首页: 网址:数据集

  7. [SinGuLaRiTy] (树形)数据结构题目复习

    [SinGuLaRiTy-1023] Copyright (c) SinGuLaRiTy 2017. All Rights Reserved. 普通平衡树 题目描述 你需要写一种数据结构(可参考题目标 ...

  8. IDEA mybatis-generator 逆向工程

    1.在maven工程中的resource中创建generatorConfig.xml 2.配置generatorConfig.xml <?xml version="1.0" ...

  9. .NET Services Stack笔记之手写版

  10. 实验吧之Canon

    解压zip文件得到一个mp3文件和一个zip压缩包,解压需要密码,那密码就在mp3里面,使用MO3Stego好像不能解析出文本,说明解析需要密码,此时通过网上的讨论说标题Canon就是密码,就试着用了 ...