httpUrlConnection连接网络的用法(用到了handle传递消息,在主线程中更新UI)

时间:2022-08-08 15:40:12

 

由于httpclient在Android5.0以后已经过时,所以官方推荐使用httpUrlConnection来连接网络,现将该连接的基本方法展示,如下

httpUrlConnection连接网络的用法(用到了handle传递消息,在主线程中更新UI)

httpUrlConnection连接网络的用法(用到了handle传递消息,在主线程中更新UI)

httpUrlConnection连接网络的用法(用到了handle传递消息,在主线程中更新UI)

 

注意:记得加入<uses-permission android:name="android.permission.INTERNET" />

另外,本例用到了handle来处理消息,跟新UI在主线程中,访问网络在子线程中

客户端代码:

 1 package imqsl.com.testhttp;
 2 
 3 import android.os.Bundle;
 4 import android.os.Handler;
 5 import android.os.Message;
 6 import android.support.v7.app.AppCompatActivity;
 7 import android.view.View;
 8 import android.widget.Button;
 9 import android.widget.EditText;
10 import android.widget.TextView;
11 import android.widget.Toast;
12 
13 import java.io.BufferedReader;
14 import java.io.DataOutputStream;
15 import java.io.IOException;
16 import java.io.InputStreamReader;
17 import java.net.HttpURLConnection;
18 import java.net.MalformedURLException;
19 import java.net.URL;
20 import java.net.URLEncoder;
21 
22 public class MainActivity extends AppCompatActivity {
23     Button button = null;
24     EditText edit = null;
25     TextView textView = null;
26     String result="";
27     Handler handler=null;
28     @Override
29     protected void onCreate(Bundle savedInstanceState) {
30         super.onCreate(savedInstanceState);
31         setContentView(R.layout.activity_main);
32         button= (Button) findViewById(R.id.button);
33         edit= (EditText) findViewById(R.id.edit);
34         textView= (TextView) findViewById(R.id.text_display);
35         button.setOnClickListener(new View.OnClickListener() {
36             @Override
37             public void onClick(View view) {
38                 if ("".equals(edit.getText().toString())){
39                     Toast.makeText(MainActivity.this,"请输入要发送的内容",Toast.LENGTH_SHORT).show();
40                     return;
41                 }
42                 new Thread(new Runnable() {
43                     @Override
44                     public void run() {
45                         send();
46                         Message msg=handler.obtainMessage();//子线程中的handle用来给主线程传递消息,虽然本例中的msg没有使用,
但是主线程中的handle也要等待该Message,否则不会继续,然后更新UI
47 handler.sendMessage(msg); 48 } 49 }).start(); 50 } 51 }); 52 handler=new Handler(){//主线程中的handle用来接收子线程中的Message以便更新UI 53 @Override 54 public void handleMessage(Message msg) { 55 Toast.makeText(MainActivity.this,result,Toast.LENGTH_SHORT).show(); 56 if (result!=null){ 57 textView.setText(result); 58 edit.setText(""); 59 } 60 super.handleMessage(msg); 61 } 62 }; 63 64 } 65 66 private void send() { 67 URL url; 68 String target = "http://192.168.1.152:8080/flightcheck/testservlet"; 69 try { 70 url=new URL(target); 71 HttpURLConnection urlConn= (HttpURLConnection) url.openConnection();//注意:httpURLconnetion的创建是这样自的 72 urlConn.setRequestMethod("POST");//设置连接方式,post必须设置,get可以不用设置,因为默认的就是get 73 urlConn.setUseCaches(false);//是指是否缓存 74 urlConn.setDoInput(true);//设置是否输入 75 urlConn.setDoOutput(true);//设置是否输出 76 DataOutputStream out=new DataOutputStream(urlConn.getOutputStream()); 77 String param="content="+ URLEncoder.encode(edit.getText().toString(),"utf-8");//使用URLEncoder.encode转换为utf-8以防止中文乱码 78 out.writeBytes(param);//writeBytes写字节到输出流中,服务器端也是接收的bytes 79 out.flush();//记得刷一下 80 out.close(); 81 System.out.println("responsecode:"+urlConn.getResponseCode()); 82 if (urlConn.getResponseCode()==HttpURLConnection.HTTP_OK){//连接成功,则相等,httpURLConnection.http_ok=200 83 BufferedReader bufferedReader=new BufferedReader(new //处理流,转换流,节点流 84 InputStreamReader(urlConn.getInputStream())); 85 String line=null; 86 System.out.println("bufferedReader.readLine():"+bufferedReader.readLine()); 87 while ((line=bufferedReader.readLine())!=null){ 88 result+=line+"\n"; //加了个"\n"相当于换到了下一行 89 } 90 } 91 } catch (MalformedURLException e) { 92 e.printStackTrace(); 93 } catch (IOException e) { 94 e.printStackTrace(); 95 } 96 97 98 } 99 }

xml文件代码:

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     android:layout_width="match_parent"
 4     android:layout_height="wrap_content"
 5     android:orientation="vertical"
 6     >
 7     <EditText
 8         android:layout_width="match_parent"
 9         android:layout_height="wrap_content"
10         android:id="@+id/edit"
11         />
12     <Button
13         android:layout_width="wrap_content"
14         android:layout_height="wrap_content"
15         android:text="发表"
16         android:id="@+id/button"
17         />
18     <TextView
19         android:layout_width="match_parent"
20         android:layout_height="wrap_content"
21         android:id="@+id/text_display"
22         />
23 
24 </LinearLayout>

服务器端代码:

 1 package test;
 2 
 3 import java.io.IOException;
 4 import java.io.PrintWriter;
 5 
 6 import javax.servlet.ServletException;
 7 import javax.servlet.http.HttpServlet;
 8 import javax.servlet.http.HttpServletRequest;
 9 import javax.servlet.http.HttpServletResponse;
10 
11 
12 public class testservlet extends HttpServlet {
13     private static final long serialVersionUID = 1L;
14 
15     public testservlet() {
16         super();
17     }
18 
19     protected void doGet(HttpServletRequest request, HttpServletResponse response)
20             throws ServletException, IOException {
21         String content = new String(request.getParameter("content").getBytes("ISO-8859-1"), "UTF-8");//客户端writeBytes,服务器端就getBytes并转码 22         System.out.println(content);
23         response.setContentType("text/plain");
24         response.setCharacterEncoding("utf-8");//加入本步设置客户端就可以得到服务器端发来的正确的中文了 25         
26         PrintWriter out=response.getWriter();//打印流,输出流,向客户端输入的意思 27         out.print(content);//输出流,向客户端输入的意思
28         out.flush();//打印流记得刷一下,不然不行 29         out.close();
30     }
31 
32     protected void doPost(HttpServletRequest request, HttpServletResponse response)
33             throws ServletException, IOException {
34         doGet(request, response);
35     }
36 
37 }