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

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

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

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

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

注意:记得加入<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);
} }
上一篇:Android中,子线程使用主线程中的组件出现问题的解决方法


下一篇:java 逆波兰表达式