Android第一次項目

来源:http://www.cnblogs.com/mff520mff/archive/2017/08/13/7352135.html
-Advertisement-
Play Games

學習了一個月的Android,接觸了人生中第一個安卓項目,對於一個小白來說,總結是很重要的學習方法,以下我把學到的東西總結以下: 1. 1》okhttp3用法解析(邊貼代碼邊熟悉) 同步Get 下載一個文件,列印他的響應頭,以string形式列印響應體。 響應體的 string() 方法對於小文檔來 ...


學習了一個月的Android,接觸了人生中第一個安卓項目,對於一個小白來說,總結是很重要的學習方法,以下我把學到的東西總結以下:

1. 1》okhttp3用法解析(邊貼代碼邊熟悉)

 

public class OkhttpService  {

public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); //json請求
public static final MediaType XML = MediaType.parse("application/xml; charset=utf-8");
private static OkhttpService instance;
private OkHttpClient client;

private OkhttpService() {
client = new OkHttpClient(); //獲取OkthhpClient實例
}
public static OkhttpService getInstance() {
return instance == null ? instance = new OkhttpService() : instance;
}

//魔盒批量封裝 (post提交json數據)
註:RequestBody body = RequestBody.create(JSON, json); //json數據為body
Request是OkHttp中訪問的請求,Builder是輔助類。Response即OkHttp中的響應。

public String insertBoxProd(List<BoxProdInfo> boxProd)throws IOException{
HttpUrl route = HttpUrl.parse("http://115.29.165.110:8085/RfService.svc/V1.0/Mh/InsertBoxProd/");
String json = new Gson().toJson(boxProd); //將boxProd序列化為json
Request request = new Request.Builder()
.url(route)
.post(RequestBody.create(JSON, json)) //使用Request的post方法來提交請求體RequestBody
.build();
Response response = client.newCall(request).execute();
boolean isOk=response.isSuccessful();
return response.body().string(); //response.body()返回ResponseBody類
}

//網點提交盒子收貨上架
public String receiverBox(String userCode, List<BoxReceiverInfo> boxReceiverInfos)throws IOException{
HttpUrl route=HttpUrl.parse("http://115.29.165.110:8085/RfService.svc/V1.0/Mh/ReceiveBox/")
.newBuilder()
.addPathSegment(userCode)
.build();
String json=new Gson().toJson(boxReceiverInfos);
Request request=new Request.Builder()
.url(route)
.put(RequestBody.create(JSON,json))
.build();
Response response=client.newCall(request).execute();
boolean isOk=response.isSuccessful();
return response.body().string();
}
}
註:以上兩個方法需要在前臺訪問。且需要返回結果提示給前臺(介面中需提供 States(返回狀態:成功或失敗),Description(結果描述),Data(數據)等)

eg:String result = OkhttpService.getInstance().receiverBox(userCode,boxReceiverInfos).toString();

2》官方文檔總結
(1)配置
導入Jar包
通過構建方式導入=== meaven

(2)基本要求
Request請求
Response響應

(3)基本使用
《--》Http GET

okHtttpClient client=new okHtttpClient();

String run(String url)throws IOException{
Request request = new Request.Builder().url(url).build();
Response response = client.newCall(request).execute();
if (response.isSuccessful()) {
return response.body().string();
}else{
throw new IOException("Unexpected code " + response);
}

}
註:Request是OkHttp中訪問的請求,Builder是輔助類,Response即OkHttp中的響應

《--》Http POST

》》》POST提交Json數據

public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
OkHttpClient client = new OkHttpClient();
String post(String url, String json) throws IOException {
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = client.newCall(request).execute();
if (response.isSuccessful())
{
return response.body().string();
} else
{
throw new IOException("Unexpected code " + response);
}
}
註:使用Request的post方法來提交請求體RequestBody

》》》POST提交鍵值對
OkHttp也可以通過POST方式把鍵值對數據傳送到伺服器

OkHttpClient client = new OkHttpClient();
String post(String url, String json) throws IOException {
RequestBody formBody = new FormEncodingBuilder()
.add("platform", "android")
.add("name", "bug")
.add("subject", "XXXXXXXXXXXXXXX")
.build();

Request request = new Request.Builder()
.url(url)
.post(body)
.build();

Response response = client.newCall(request).execute();
if (response.isSuccessful())
{
return response.body().string();
} else {
throw new IOException("Unexpected code " + response);
}
}

(3)案例

佈局文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<LinearLayout android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="horizontal">
<Button android:id="@+id/bt_get"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="烏雲Get請求"/>

<Button android:id="@+id/bt_post"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="烏雲Post請求"/>

LinearLayout>

<TextView android:id="@+id/tv_show"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>

LinearLayout>

Java代碼:
由於android本身是不允許在UI線程做網路請求操作的,所以我們自己寫個線程完成網路操作

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

private Button bt_get;
private Button bt_post;
final OkHttpClient client = new OkHttpClient();

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
bt_get=(Button)findViewById(R.id.bt_get);
bt_post=(Button)findViewById(R.id.bt_post);
bt_get.setOnClickListener(this);
bt_post.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.bt_get:
getRequest();
break;

case R.id.bt_post:
postRequest();
break;
}
}
private void getRequest() {
final Request request=new Request.Builder()
.get()
.tag(this)
.url("http://www.wooyun.org")
.build();
new Thread(new Runnable() {
@Override
public void run() {
Response response = null;
try {
response = client.newCall(request).execute();
if (response.isSuccessful()) {
Log.i("WY","列印GET響應的數據:" + response.body().string());
} else {
throw new IOException("Unexpected code " + response);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}

private void postRequest() {
RequestBody formBody = new FormEncodingBuilder()
.add("","")
.build();
final Request request = new Request.Builder()
.url("http://www.wooyun.org")
.post(formBody)
.build();
new Thread(new Runnable() {
@Override
public void run() {
Response response = null;
try {
response = client.newCall(request).execute();
if (response.isSuccessful()) {
Log.i("WY","列印POST響應的數據:" + response.body().string());
} else {
throw new IOException("Unexpected code " + response);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
}

剩下的簡單說明:

   同步Get

       下載一個文件,列印他的響應頭,以string形式列印響應體。
       響應體的 string() 方法對於小文檔來說十分方便、高效。但是如果響應體太大(超過1MB),應避免適應 string()方法 ,因為他會將把整個文檔載入到記憶體中。對於超過1MB的響應    body,應使用流的方式來處理body。

   非同步Get

    在一個工作線程中下載文件,當響應可讀時回調Callback介面。讀取響應時會阻塞當前線程。OkHttp現階段不提供非同步api來接收響應體。

    

   提取響應頭

   典型的HTTP頭 像是一個 Map

    

      Post方式提交String

        使用HTTP POST提交請求到服務。這個例子提交了一個markdown文檔到web服務,以HTML方式渲染markdown。因為整個請求體都在記憶體中,因此避免使用此api提交大文        檔 (大於1MB)。

 

     待續。。。。。。。。。

     部分出自  http://m.2cto.com/net/201605/505364.html

 






       



 

                     

 

 


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

-Advertisement-
Play Games
更多相關文章
  • JavaScript表單 這篇文章的主要目的是介紹表單相關的知識,如表單基礎知識、文本框腳本相關用法、選擇框腳本相關用法以及等知識。雖然在現代web開發中,很少會使用form預設行為提交表單數據,而是會禁用預設行為,然後使用Ajax方式通過POST請求非同步提交表單數據。但是這並不代表form表單不重 ...
  • 轉自:http://www.cnblogs.com/linhaixin/p/5581939.html 獲取(代碼): 修改(代碼): ...
  • 在Android中,共有五種佈局方式,分別是:LinearLayout(線性佈局),FrameLayout(幀佈局),AbsoluteLayout(絕對佈局),RelativeLayout(相對佈局), TableLayout(表格佈局);還有一種,是在Android4.0以後出現的新佈局:Grid ...
  • 一,工程圖。 二,代碼。 ViewController.h ViewController.m ...
  • ...
  • (1)下載二維碼的庫源碼 鏈接:http://pan.baidu.com/s/1pKQyw2n 密碼:r5bv 下載完成後打開可以看到 libzxing 的文件夾,最後添加進 Android Studio,操作 :File 》New 》Import Moudle (2)按鈕單擊事件為 scanner ...
  • SharedPreferences是Android四種數據存儲技術中的一種,它是一種輕型的數據存儲方式,它的本質是基於XML文件存儲key-value鍵值對數據,通常用來存儲一些簡單的配置信 息,其對象本身只能獲取數據,不支持存儲和修改,存儲和修改需要通過 Edit 對象來實現,例如用戶登錄時對賬號 ...
  • 1. Android中如何從一個Activity中ArrayList<HashMap<String,Object>>傳遞到另一個activity? eg: 存:intent.putExtra("arrayList", dataList); 取(記得強制類型轉換): ArrayList<HashMap ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...