android http同步請求

来源:http://www.cnblogs.com/zhongyinghe/archive/2016/03/19/5294567.html
-Advertisement-
Play Games

1、界面 2、MainActivity代碼,用來響應button代碼 3、http請求同步代碼 4、把輸入流轉換為字元串 5、清單文件 <uses-permission android:name="android.permission.INTERNET"/>//許可權 最後:一般來說,子線程是無法改變


1、界面

 1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 2     xmlns:tools="http://schemas.android.com/tools"
 3     android:layout_width="match_parent"
 4     android:orientation="vertical"
 5     android:layout_height="match_parent"
 6     tools:context=".MainActivity" >
 7 
 8     <EditText
 9         android:id="@+id/et_username"
10         android:layout_width="match_parent"
11         android:layout_height="wrap_content"
12         android:hint="請輸入用戶名"
13         android:text="張三"
14          />
15   
16 
17     <EditText
18         android:id="@+id/et_password"
19         android:layout_width="match_parent"
20         android:layout_height="wrap_content"
21         android:hint="請輸入密碼"
22         android:inputType="textPassword" />
23 
24     <Button
25         android:onClick="myGetData"
26         android:id="@+id/button1"
27         android:layout_width="wrap_content"
28         android:layout_height="wrap_content"
29         android:text="登陸" />
30 
31 </LinearLayout>

2、MainActivity代碼,用來響應button代碼

 1 package com.example.getdata;
 2 
 3 import java.net.HttpURLConnection;
 4 import java.net.MalformedURLException;
 5 import java.net.URL;
 6 
 7 import com.example.getdata.service.LoginService;
 8 
 9 import android.os.Bundle;
10 import android.os.Handler;
11 import android.os.Message;
12 import android.app.Activity;
13 import android.view.Menu;
14 import android.view.View;
15 import android.widget.EditText;
16 import android.widget.Toast;
17 
18 public class MainActivity extends Activity {
19 
20     private EditText et_username;
21     private EditText et_password;
22     /*private Handler handler = new Handler(){
23 
24         @Override
25         public void handleMessage(android.os.Message msg) {
26             // TODO Auto-generated method stub
27             
28         }
29         
30     };*/
31     @Override
32     protected void onCreate(Bundle savedInstanceState) {
33         super.onCreate(savedInstanceState);
34         setContentView(R.layout.activity_main);
35         et_username = (EditText)findViewById(R.id.et_username);
36         et_password = (EditText)findViewById(R.id.et_password);
37     }
38 
39 
40     public void myGetData(View view){
41         final String username = et_username.getText().toString().trim();
42         final String password = et_password.getText().toString().trim();
43         System.out.println("username:" + username);
44         System.out.println("password:" + password);
45         new Thread(){
46             public void run(){
47                 //final String result = LoginService.loginByGet(username, password);
48                 //final String result = LoginService.loginByPost(username, password);
49                 //final String result = LoginService.loginByClientGet(username, password);
50                 final String result = LoginService.loginByClientPost(username, password);
51                 if(result != null){
52                     runOnUiThread(new Runnable(){
53                         @Override
54                         public void run() {
55                             // TODO Auto-generated method stub
56                             Toast.makeText(MainActivity.this, result, 0).show();
57                         }
58                         
59                     });
60                 }else{
61                     runOnUiThread(new Runnable(){
62                         @Override
63                         public void run() {
64                             // TODO Auto-generated method stub
65                             Toast.makeText(MainActivity.this, "請求不成功!", 0).show();
66                         }
67                         
68                     });
69                 }
70             };
71         }.start();
72     }
73     
74 }

3、http請求同步代碼

  1 package com.example.getdata.service;
  2 
  3 import java.io.IOException;
  4 import java.io.InputStream;
  5 import java.io.OutputStream;
  6 import java.io.UnsupportedEncodingException;
  7 import java.net.HttpURLConnection;
  8 import java.net.URL;
  9 import java.net.URLEncoder;
 10 import java.util.ArrayList;
 11 import java.util.List;
 12 
 13 import org.apache.http.HttpResponse;
 14 import org.apache.http.NameValuePair;
 15 import org.apache.http.client.ClientProtocolException;
 16 import org.apache.http.client.HttpClient;
 17 import org.apache.http.client.entity.UrlEncodedFormEntity;
 18 import org.apache.http.client.methods.HttpGet;
 19 import org.apache.http.client.methods.HttpPost;
 20 import org.apache.http.impl.client.DefaultHttpClient;
 21 import org.apache.http.message.BasicNameValuePair;
 22 
 23 import com.example.getdata.utils.StreamTools;
 24 /*
 25  * 註意事項:在發送請求時,如果有中文,註意把它轉換為相應的編碼
 26  */
 27 public class LoginService {
 28     
 29     public static String loginByGet(String username, String password){
 30         try {
 31             String path = "http://192.168.1.100/android/index.php?username=" + URLEncoder.encode(username, "utf-8") + "&password=" + password;
 32             URL url = new URL(path);
 33             HttpURLConnection conn = (HttpURLConnection)url.openConnection();
 34             conn.setRequestMethod("GET");
 35             conn.setReadTimeout(5000);
 36             //conn.setRequestProperty(field, newValue);
 37             int code = conn.getResponseCode();
 38             if(code == 200){
 39                 InputStream is = conn.getInputStream();
 40                 String result = StreamTools.readInputStream(is);
 41                 return result;
 42             }else{
 43                 return null;
 44             }
 45         } catch (Exception e) {
 46             // TODO Auto-generated catch block
 47             e.printStackTrace();
 48             return null;
 49         }
 50         
 51     }
 52     
 53     public static String loginByPost(String username, String password){
 54         String path = "http://192.168.1.101/android/index.php";
 55         try {
 56             URL url = new URL(path);
 57             HttpURLConnection conn = (HttpURLConnection)url.openConnection();
 58             conn.setRequestMethod("POST");
 59             conn.setReadTimeout(5000);
 60             conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
 61             String data = "username=" + URLEncoder.encode(username, "utf-8") + "&password=" + password;
 62             conn.setRequestProperty("Content-Length", data.length() + "");
 63             //允許向外面寫數據
 64             conn.setDoOutput(true);
 65             //獲取輸出流
 66             OutputStream os = conn.getOutputStream();
 67             os.write(data.getBytes());
 68             int code = conn.getResponseCode();
 69             if(code == 200){
 70                 InputStream is = conn.getInputStream();
 71                 String result = StreamTools.readInputStream(is);
 72                 return result;
 73             }else{
 74                 System.out.println("----111");
 75                 return null;
 76             }
 77         } catch (Exception e) {
 78             // TODO Auto-generated catch block
 79             e.printStackTrace();
 80             System.out.println("----2222");
 81             return null;
 82         }
 83         
 84     }
 85     
 86     public static String loginByClientGet(String username, String password){
 87         try{
 88             //1、打開一個瀏覽器
 89             HttpClient client = new DefaultHttpClient();
 90             
 91             //輸入地址ַ
 92             String path = "http://192.168.1.101/android/index.php?username=" + URLEncoder.encode(username, "utf-8") + "&password=" + password;
 93             HttpGet httpGet = new HttpGet(path);
 94             
 95             //敲回車
 96             HttpResponse response = client.execute(httpGet);
 97             
 98             //獲取返回狀態碼
 99             int code = response.getStatusLine().getStatusCode();
100             if(code == 200){
101                 InputStream is = response.getEntity().getContent();
102                 String result = StreamTools.readInputStream(is);
103                 return result;
104             }else{
105                 System.out.println("----111");
106                 return null;
107             }
108         }catch(Exception e){
109             e.printStackTrace();
110             System.out.println("----222");
111             return null;
112         }
113         
114     }
115     
116     public static String loginByClientPost(String username, String password){
117         try {
118             //�������
119             HttpClient client = new DefaultHttpClient();
120             
121             //�����ַ
122             String path = "http://192.168.1.101/android/index.php";
123             HttpPost httpPost = new HttpPost(path);
124             //ָ��Ҫ�ύ�����ʵ��
125             List<NameValuePair> parameters = new ArrayList<NameValuePair>();
126             parameters.add(new BasicNameValuePair("username",username));
127             parameters.add(new BasicNameValuePair("password",password));
128             
129             httpPost.setEntity(new UrlEncodedFormEntity(parameters,"utf-8"));
130             HttpResponse response = client.execute(httpPost);
131             //��ȡ�������
132             int code = response.getStatusLine().getStatusCode();
133             if(code == 200){
134                 InputStream is = response.getEntity().getContent();
135                 String result = StreamTools.readInputStream(is);
136                 return result;
137             }else{
138                 System.out.println("----111");
139                 return null;
140             }
141         } catch (Exception e) {
142             // TODO Auto-generated catch block
143             System.out.println("----222");
144             e.printStackTrace();
145             return null;
146         }
147     }
148 }

4、把輸入流轉換為字元串

package com.example.getdata.utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class StreamTools {
    /*
     * 功能:把inputStream轉化為字元串
     */
    public static String readInputStream(InputStream is){
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int len=0;
            byte[] buffer = new byte[1024];
            while((len = is.read(buffer)) != -1){
                baos.write(buffer, 0, len);
            }
            baos.close();
            is.close();
            byte[] result = baos.toByteArray();
            return new String(result);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return null;
        }
        
    }
}

 5、清單文件

<uses-permission android:name="android.permission.INTERNET"/>//許可權

最後:一般來說,子線程是無法改變UI的,但是這裡採用runOnUiThread方式是可以的,而不是採用發送消息的方式


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • hover3d.js是一款效果超酷的滑鼠滑過圖片3D卡片效果jQuery插件。通過該插件可以製作出滑鼠滑過圖片時,圖片3D傾斜,旋轉的效果,非常有層次感。 使用該jQuery插件需要在頁面中引入jquery和jquery.hover3d.min.js文件 該滑鼠滑過圖片效果的HTML結構如下:包裹元
  • 我的博客: "http://bigdots.github.io" 、 "http://www.cnblogs.com/yzg1/" 繼承有什麼好處?很簡單,繼承了你爸的財產,自己就可以少奮鬥點嘛。開玩笑,言歸正傳,繼承使子類擁有超類的作用域、屬性與方法,可以節省程式設計的時間。ECMAScript實
  • 問題: 在做即時通訊時,需要提示用戶有幾條未讀的提醒,這個是(如果有新的提示消息立馬在瀏覽器無刷新提示)即時獲取的。但我們的做法是,當用戶點擊未讀信息進入到信息顯示頁面時重新獲取下未讀的提醒;但是在IE瀏覽器下,在新視窗打開以後沒有重新獲取請求,再次刷新頁面也沒有看到請求地址。但是如果將鏈接打開方式
  • "Whenever this property changes, apply that change slowly." The property transition: width 2s says “when the width changes, animate it over the course
  • 分類:C#、Android、VS2015; 創建日期:2016-03-19 一、簡介 Android系統定義了一系列獨立的圖形處理類,其中,2D圖形處理類分別位於以下命名空間: Android.Graphices Android.Graphics.Drawable.Shapes Android.Vi...
  • 1.安卓中文件的數據存儲實例(將文件保存到手機自帶存儲空間中): ①MainActivity.java public class MainActivity extends Activity implements OnClickListener{ private Button mButton; pri
  • 最好不要在UIViewController的loadView方法中改變狀態欄的可視性(比如狀態欄由顯示變為隱藏、或者由隱藏變為顯示),因為這樣的操作會導致重覆調用2次loadView和viewDidLoad方法。 雖然運行效果是對的,但是系統連續調用了2次loadView和viewDidLoad方法
  • 猴年支付寶可算是給大家一個很好的驚喜,刺激。大家都在為敬業福而四處奔波。可是到最後也沒有幾個得到敬業福德,就像我。不知道大家有沒有觀察,五福界面的滾動是一個很好的設計。在這裡,給大家帶來簡單的滾動實現,首先看一下實現效果。 通過觀察不難發現,有很多地方並不是那麼容易想出來的,對於篇隨筆,感興趣可以查
一周排行
    -Advertisement-
    Play Games
  • 前言 本文介紹一款使用 C# 與 WPF 開發的音頻播放器,其界面簡潔大方,操作體驗流暢。該播放器支持多種音頻格式(如 MP4、WMA、OGG、FLAC 等),並具備標記、實時歌詞顯示等功能。 另外,還支持換膚及多語言(中英文)切換。核心音頻處理採用 FFmpeg 組件,獲得了廣泛認可,目前 Git ...
  • OAuth2.0授權驗證-gitee授權碼模式 本文主要介紹如何筆者自己是如何使用gitee提供的OAuth2.0協議完成授權驗證並登錄到自己的系統,完整模式如圖 1、創建應用 打開gitee個人中心->第三方應用->創建應用 創建應用後在我的應用界面,查看已創建應用的Client ID和Clien ...
  • 解決了這個問題:《winForm下,fastReport.net 從.net framework 升級到.net5遇到的錯誤“Operation is not supported on this platform.”》 本文內容轉載自:https://www.fcnsoft.com/Home/Sho ...
  • 國內文章 WPF 從裸 Win 32 的 WM_Pointer 消息獲取觸摸點繪製筆跡 https://www.cnblogs.com/lindexi/p/18390983 本文將告訴大家如何在 WPF 裡面,接收裸 Win 32 的 WM_Pointer 消息,從消息裡面獲取觸摸點信息,使用觸摸點 ...
  • 前言 給大家推薦一個專為新零售快消行業打造了一套高效的進銷存管理系統。 系統不僅具備強大的庫存管理功能,還集成了高性能的輕量級 POS 解決方案,確保頁面載入速度極快,提供良好的用戶體驗。 項目介紹 Dorisoy.POS 是一款基於 .NET 7 和 Angular 4 開發的新零售快消進銷存管理 ...
  • ABP CLI常用的代碼分享 一、確保環境配置正確 安裝.NET CLI: ABP CLI是基於.NET Core或.NET 5/6/7等更高版本構建的,因此首先需要在你的開發環境中安裝.NET CLI。這可以通過訪問Microsoft官網下載並安裝相應版本的.NET SDK來實現。 安裝ABP ...
  • 問題 問題是這樣的:第三方的webapi,需要先調用登陸介面獲取Cookie,訪問其它介面時攜帶Cookie信息。 但使用HttpClient類調用登陸介面,返回的Headers中沒有找到Cookie信息。 分析 首先,使用Postman測試該登陸介面,正常返回Cookie信息,說明是HttpCli ...
  • 國內文章 關於.NET在中國為什麼工資低的分析 https://www.cnblogs.com/thinkingmore/p/18406244 .NET在中國開發者的薪資偏低,主要因市場需求、技術棧選擇和企業文化等因素所致。歷史上,.NET曾因微軟的閉源策略發展受限,儘管後來推出了跨平臺的.NET ...
  • 在WPF開發應用中,動畫不僅可以引起用戶的註意與興趣,而且還使軟體更加便於使用。前面幾篇文章講解了畫筆(Brush),形狀(Shape),幾何圖形(Geometry),變換(Transform)等相關內容,今天繼續講解動畫相關內容和知識點,僅供學習分享使用,如有不足之處,還請指正。 ...
  • 什麼是委托? 委托可以說是把一個方法代入另一個方法執行,相當於指向函數的指針;事件就相當於保存委托的數組; 1.實例化委托的方式: 方式1:通過new創建實例: public delegate void ShowDelegate(); 或者 public delegate string ShowDe ...