如果你看到這一片文章,但是你還對http協議的基本知識以及通過url獲取網絡數據還不是很瞭解,請先看一下上面兩篇文章:Android中的Http通信(一)之Http協議基本知識、 Android中的Http通信(二)之根據Url讀取網絡數據。
本文主要介紹的是通過http中的GET方式和POST方式上傳數據到服務器,其中涉及到解決服務器亂碼問題。本文需要服務器和Android前端配合,由於這裏是寫Android方面的問題,後臺服務器我就寫了一個簡單的demo,在文章最後大家可以自行下載,這裏不在累述(其實是本人的服務器的功底.....)。廢話不多說,直接開幹。
遵循上一篇的習慣,先來一個佈局吧:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="用戶名:肖運飛\n密碼:123456" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:orientation="horizontal" >
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center_horizontal"
android:text="用戶名:" />
<EditText
android:id="@+id/name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:hint="用戶名" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:orientation="horizontal" >
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center_horizontal"
android:text="密碼:" />
<EditText
android:id="@+id/pwd"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:hint="密碼" />
</LinearLayout>
<Button
android:id="@+id/get_btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:gravity="center"
android:text="GET 登錄" />
<Button
android:id="@+id/post_btn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:gravity="center"
android:text="POST 登錄" />
<TextView
android:id="@+id/response"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp" />
</LinearLayout>
很簡單,不做任何介紹,如果看不懂的話,先補習補習,再往下看。
下面是Ativity中的代碼:
package com.example.http;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
/**
* 測試http的get、post的類
*
* @author xiaoyf
*
*/
public class MainActivity extends Activity {
private EditText name;
private EditText pwd;
private Button get_btn;
private Button post_btn;
private TextView response;
private Handler handler = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = (EditText) findViewById(R.id.name);
pwd = (EditText) findViewById(R.id.pwd);
get_btn = (Button) findViewById(R.id.get_btn);
post_btn = (Button) findViewById(R.id.post_btn);
response = (TextView) findViewById(R.id.response);
get_btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String url = "http://192.168.1.2:8080/WebProject/MyServlet";
new HttpThread(url, name.getText().toString(), pwd.getText()
.toString(), response, handler, 1).start();
}
});
post_btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Log.d("bbb", "onClick");
String url = "http://192.168.1.2:8080/WebProject/MyServlet";
new HttpThread(url, name.getText().toString(), pwd.getText()
.toString(), response, handler, 2).start();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
下面是GET、POST傳遞參數的核心代碼,也是本篇的核心。
package com.example.http;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import android.os.Handler;
import android.util.Log;
import android.webkit.WebView;
import android.widget.TextView;
/**
* 測試http的get、post的線程
*
* @author xiaoyf
*
*/
public class HttpThread extends Thread {
private final static int CONNECT_OUT_TIME = 5000;
private String url;
private String name;
private String pwd;
private TextView response;
private Handler handler;
/**
* tag=1:默認,get方式;tag=2:post方式
*/
private int tag = 1;
public HttpThread() {
super();
}
public HttpThread(String url, String name, String pwd, TextView response,
Handler handler, int tag) {
super();
this.url = url;
this.name = name;
this.pwd = pwd;
this.response = response;
this.handler = handler;
this.tag = tag;
}
public void doGet() {
// 如果服務器沒有轉碼的時候,我們可以設置,防止亂碼
// name = URLEncoder.encode(name, "utf-8");
// pwd = URLEncoder.encode(pwd, "utf-8");
url += "?name=" + name + "&pwd=" + pwd;
try {
// 第一步:創建必要的URL對象
URL httpUrl = new URL(url);
// 第二步:根據URL對象,獲取HttpURLConnection對象
HttpURLConnection connection = (HttpURLConnection) httpUrl
.openConnection();
// 第三步:爲HttpURLConnection對象設置必要的參數(是否允許輸入數據、連接超時時間、請求方式)
connection.setConnectTimeout(CONNECT_OUT_TIME);
connection.setReadTimeout(CONNECT_OUT_TIME);
connection.setRequestMethod("GET");
connection.setDoInput(true);
// 第四步:開始讀取服務器返回數據
BufferedReader reader = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
final StringBuffer buffer = new StringBuffer();
String str = null;
while ((str = reader.readLine()) != null) {
buffer.append(str);
}
reader.close();
handler.post(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
response.setText(buffer.toString());
}
});
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void doPost() {
try {
// 第一步:創建必要的URL對象
URL httpUrl = new URL(url);
// 第二步:根據URL對象,獲取HttpURLConnection對象
HttpURLConnection connection = (HttpURLConnection) httpUrl
.openConnection();
// 第三步:爲HttpURLConnection對象設置必要的參數(是否允許輸入數據、連接超時時間、請求方式)
connection.setConnectTimeout(CONNECT_OUT_TIME);
connection.setReadTimeout(CONNECT_OUT_TIME);
connection.setRequestMethod("POST");
connection.setDoInput(true);
// 第四步:向服務器寫入數據
OutputStream out = connection.getOutputStream();
String content = "name=" + name + "&pwd=" + pwd;// 無論服務器轉碼與否,這裏不需要轉碼,因爲Android系統自動已經轉碼爲utf-8啦
out.write(content.getBytes());
out.flush();
out.close();
// 第五步:開始讀取服務器返回數據
BufferedReader reader = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
final StringBuffer buffer = new StringBuffer();
String str = null;
while ((str = reader.readLine()) != null) {
buffer.append(str);
}
reader.close();
handler.post(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
response.setText(buffer.toString());
}
});
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void run() {
// TODO Auto-generated method stub
if (tag == 1) http://
doGet();
else if (tag == 2)
doPost();
}
}
GET、POST傳遞參數的時候的區別:
兩者的URL:
GET:基本的url+參數的拼接;
POST:基本的url
是否攜帶輸出流:
GET:不需要;
POST:參數的拼接然後轉化爲字節數組