HttpUrlConnection get,post傳輸
這裡沒有寫UI操作,get請求中文亂碼問題這裡也沒有處理,如果做UI操作,需要在子線程中,這裡主要講解get,post如何傳遞資料,其他知識就不考慮了
package com.example.httpurlconnectiontest;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStream;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.ProtocolException;import java.net.URL;import android.content.Context;import android.widget.Toast;/** * 使用HttpUrlConnection實現get,post方式傳遞資料 * @author Administrator * */public class HttpThread extends Thread{private String url;private String name;private String age;private Context context;public HttpThread(Context context, String url, String name, String age) {this.context =context;this.url = url;this.name = name;this.age = age;}private void doGet(){url = url+"?username="+name+"&password="+age;try {URL httpUrl = new URL(url);HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();conn.setRequestMethod("GET");conn.setReadTimeout(5000);BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));String str;StringBuffer sb = new StringBuffer();while((str = reader.readLine())!=null){sb.append(str);}System.out.println(sb);} catch (MalformedURLException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}private void doPost(){try {URL httpUrl = new URL(url);HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();conn.setRequestMethod("POST");conn.setReadTimeout(5000);OutputStream out = conn.getOutputStream();String content ="username="+name+"&password="+age;out.write(content.getBytes());BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));String str;StringBuffer sb = new StringBuffer();while((str = reader.readLine())!=null){sb.append(str);}System.out.println(sb);} catch (MalformedURLException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (ProtocolException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}@Overridepublic void run() {// TODO Auto-generated method stub//doGet();doPost();}}在MainActivity中調用:
String url = "http://115.158.57.173:8080/KuaiDi3/AddUser_servlet";new HttpThread(MainActivity.this,url, "123", "123").start();