Android第一次項目,android第一次

來源:互聯網
上載者:User

Android第一次項目,android第一次

學習了一個月的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

 






       



 

                     

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.