Android發(fā)送GET與POST請求的DEMO詳解
更新時間:2013年06月14日 16:50:29 作者:
本篇文章是對Android發(fā)送GET與POST請求的DEMO進行了詳細(xì)的分析介紹,需要的朋友參考下
4.0后網(wǎng)絡(luò)訪問必須單獨起一個子線程訪問,否則無法運行,這里有一個發(fā)送請求的工具類GetPostUtil
public class GetPostUtil
{
/**
* 向指定URL發(fā)送GET方法的請求
*
* @param url
* 發(fā)送請求的URL
* @param params
* 請求參數(shù),請求參數(shù)應(yīng)該是name1=value1&name2=value2的形式。
* @return URL所代表遠程資源的響應(yīng)
*/
public static String sendGet(String url, String params)
{
String result = "";
BufferedReader in = null;
try
{
String urlName = url + "?" + params;
URL realUrl = new URL(urlName);
// 打開和URL之間的連接
URLConnection conn = realUrl.openConnection();
// 設(shè)置通用的請求屬性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
// 建立實際的連接
conn.connect();
// 獲取所有響應(yīng)頭字段
Map<String, List<String>> map = conn.getHeaderFields();
// 遍歷所有的響應(yīng)頭字段
for (String key : map.keySet())
{
System.out.println(key + "--->" + map.get(key));
}
// 定義BufferedReader輸入流來讀取URL的響應(yīng)
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null)
{
result += "\n" + line;
}
}
catch (Exception e)
{
System.out.println("發(fā)送GET請求出現(xiàn)異常!" + e);
e.printStackTrace();
}
// 使用finally塊來關(guān)閉輸入流
finally
{
try
{
if (in != null)
{
in.close();
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
return result;
}
/**
* 向指定URL發(fā)送POST方法的請求
*
* @param url
* 發(fā)送請求的URL
* @param params
* 請求參數(shù),請求參數(shù)應(yīng)該是name1=value1&name2=value2的形式。
* @return URL所代表遠程資源的響應(yīng)
*/
public static String sendPost(String url, String params)
{
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try
{
URL realUrl = new URL(url);
// 打開和URL之間的連接
URLConnection conn = realUrl.openConnection();
// 設(shè)置通用的請求屬性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
// 發(fā)送POST請求必須設(shè)置如下兩行
conn.setDoOutput(true);
conn.setDoInput(true);
// 獲取URLConnection對象對應(yīng)的輸出流
out = new PrintWriter(conn.getOutputStream());
// 發(fā)送請求參數(shù)
out.print(params);
// flush輸出流的緩沖
out.flush();
// 定義BufferedReader輸入流來讀取URL的響應(yīng)
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null)
{
result += "\n" + line;
}
}
catch (Exception e)
{
System.out.println("發(fā)送POST請求出現(xiàn)異常!" + e);
e.printStackTrace();
}
// 使用finally塊來關(guān)閉輸出流、輸入流
finally
{
try
{
if (out != null)
{
out.close();
}
if (in != null)
{
in.close();
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
return result;
}
}
Activity類代碼
public class GetPostMain extends Activity
{
Button get , post;
EditText show;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
get = (Button) findViewById(R.id.get);
post = (Button) findViewById(R.id.post);
show = (EditText)findViewById(R.id.show);
//利用Handler更新UI
final Handler h = new Handler(){
@Override
public void handleMessage(Message msg) {
if(msg.what==0x123){
show.setText(msg.obj.toString());
}
}
};
get.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
new Thread(new AccessNetwork("GET", "http://192.168.1.88:8080/abc/a.jsp", null, h)).start();
}
});
post.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
new Thread(new AccessNetwork("POST", "http://192.168.1.88:8080/abc/login.jsp", "name=crazyit.org&pass=leegang", h)).start();
}
});
}
}
class AccessNetwork implements Runnable{
private String op ;
private String url;
private String params;
private Handler h;
public AccessNetwork(String op, String url, String params,Handler h) {
super();
this.op = op;
this.url = url;
this.params = params;
this.h = h;
}
@Override
public void run() {
Message m = new Message();
m.what = 0x123;
if(op.equals("GET")){
Log.i("iiiiiii","發(fā)送GET請求");
m.obj = GetPostUtil.sendGet(url, params);
Log.i("iiiiiii",">>>>>>>>>>>>"+m.obj);
}
if(op.equals("POST")){
Log.i("iiiiiii","發(fā)送POST請求");
m.obj = GetPostUtil.sendPost(url, params);
Log.i("gggggggg",">>>>>>>>>>>>"+m.obj);
}
h.sendMessage(m);
}
}
復(fù)制代碼 代碼如下:
public class GetPostUtil
{
/**
* 向指定URL發(fā)送GET方法的請求
*
* @param url
* 發(fā)送請求的URL
* @param params
* 請求參數(shù),請求參數(shù)應(yīng)該是name1=value1&name2=value2的形式。
* @return URL所代表遠程資源的響應(yīng)
*/
public static String sendGet(String url, String params)
{
String result = "";
BufferedReader in = null;
try
{
String urlName = url + "?" + params;
URL realUrl = new URL(urlName);
// 打開和URL之間的連接
URLConnection conn = realUrl.openConnection();
// 設(shè)置通用的請求屬性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
// 建立實際的連接
conn.connect();
// 獲取所有響應(yīng)頭字段
Map<String, List<String>> map = conn.getHeaderFields();
// 遍歷所有的響應(yīng)頭字段
for (String key : map.keySet())
{
System.out.println(key + "--->" + map.get(key));
}
// 定義BufferedReader輸入流來讀取URL的響應(yīng)
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null)
{
result += "\n" + line;
}
}
catch (Exception e)
{
System.out.println("發(fā)送GET請求出現(xiàn)異常!" + e);
e.printStackTrace();
}
// 使用finally塊來關(guān)閉輸入流
finally
{
try
{
if (in != null)
{
in.close();
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
return result;
}
/**
* 向指定URL發(fā)送POST方法的請求
*
* @param url
* 發(fā)送請求的URL
* @param params
* 請求參數(shù),請求參數(shù)應(yīng)該是name1=value1&name2=value2的形式。
* @return URL所代表遠程資源的響應(yīng)
*/
public static String sendPost(String url, String params)
{
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try
{
URL realUrl = new URL(url);
// 打開和URL之間的連接
URLConnection conn = realUrl.openConnection();
// 設(shè)置通用的請求屬性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
// 發(fā)送POST請求必須設(shè)置如下兩行
conn.setDoOutput(true);
conn.setDoInput(true);
// 獲取URLConnection對象對應(yīng)的輸出流
out = new PrintWriter(conn.getOutputStream());
// 發(fā)送請求參數(shù)
out.print(params);
// flush輸出流的緩沖
out.flush();
// 定義BufferedReader輸入流來讀取URL的響應(yīng)
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null)
{
result += "\n" + line;
}
}
catch (Exception e)
{
System.out.println("發(fā)送POST請求出現(xiàn)異常!" + e);
e.printStackTrace();
}
// 使用finally塊來關(guān)閉輸出流、輸入流
finally
{
try
{
if (out != null)
{
out.close();
}
if (in != null)
{
in.close();
}
}
catch (IOException ex)
{
ex.printStackTrace();
}
}
return result;
}
}
Activity類代碼
復(fù)制代碼 代碼如下:
public class GetPostMain extends Activity
{
Button get , post;
EditText show;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
get = (Button) findViewById(R.id.get);
post = (Button) findViewById(R.id.post);
show = (EditText)findViewById(R.id.show);
//利用Handler更新UI
final Handler h = new Handler(){
@Override
public void handleMessage(Message msg) {
if(msg.what==0x123){
show.setText(msg.obj.toString());
}
}
};
get.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
new Thread(new AccessNetwork("GET", "http://192.168.1.88:8080/abc/a.jsp", null, h)).start();
}
});
post.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
new Thread(new AccessNetwork("POST", "http://192.168.1.88:8080/abc/login.jsp", "name=crazyit.org&pass=leegang", h)).start();
}
});
}
}
class AccessNetwork implements Runnable{
private String op ;
private String url;
private String params;
private Handler h;
public AccessNetwork(String op, String url, String params,Handler h) {
super();
this.op = op;
this.url = url;
this.params = params;
this.h = h;
}
@Override
public void run() {
Message m = new Message();
m.what = 0x123;
if(op.equals("GET")){
Log.i("iiiiiii","發(fā)送GET請求");
m.obj = GetPostUtil.sendGet(url, params);
Log.i("iiiiiii",">>>>>>>>>>>>"+m.obj);
}
if(op.equals("POST")){
Log.i("iiiiiii","發(fā)送POST請求");
m.obj = GetPostUtil.sendPost(url, params);
Log.i("gggggggg",">>>>>>>>>>>>"+m.obj);
}
h.sendMessage(m);
}
}
相關(guān)文章
Android Studio新建工程默認(rèn)在build.gradle中加入maven阿里源的問題
這篇文章主要介紹了Android Studio新建工程默認(rèn)在build.gradle中加入maven阿里源的問題,本文通過實例代碼相結(jié)合給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-03-03Android編程獲取包名,版本信息及VersionName名稱的方法
這篇文章主要介紹了Android編程獲取包名,版本信息及VersionName名稱的方法,涉及Android包及版本相關(guān)操作函數(shù)使用技巧,需要的朋友可以參考下2016-10-10Android ProgressBar 模擬進度條效果的實現(xiàn)
這篇文章主要介紹了Android ProgressBar 模擬進度條效果的實現(xiàn),本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-04-04Android中使用PopupWindow 仿微信點贊和評論彈出
微信朋友圈的點贊和評論功能,有2個組成部分:左下角的“更多”按鈕;點擊該按鈕后彈出的對話框。這篇文章主要介紹了Android中使用PopupWindow 仿微信點贊和評論彈出,需要的朋友可以參考下2017-04-04淺談Android獲取ImageView上的圖片,和一個有可能遇到的問題
下面小編就為大家?guī)硪黄獪\談Android獲取ImageView上的圖片,和一個有可能遇到的問題。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-04-04Android TabLayout實現(xiàn)京東詳情效果
這篇文章主要為大家詳細(xì)介紹了android TabLayout實現(xiàn)京東詳情效果,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-09-09實例講解Android中的AIDL內(nèi)部進程通信接口使用
這篇文章主要通過實例介紹了Android中的AIDL內(nèi)部進程通信接口使用,文中通過一個音樂播放的服務(wù)編寫例子來講解AIDL的傳遞對象及一般使用步驟,需要的朋友可以參考下2016-04-04