First Android project, first android Project

Source: Internet
Author: User
Tags call back tojson

First Android project, first android Project

I learned Android for a month and got into touch with the first Android project in my life. For a Tom, the summary is an important learning method. I will summarize what I have learned as follows:

1. 1 okhttp3 Usage Analysis (familiar with code)

 

Public class OkhttpService {

Public static final MediaType JSON = MediaType. parse ("application/json; charset = UTF-8"); // json request
Public static final MediaType XML = MediaType. parse ("application/xml; charset = UTF-8 ");
Private static OkhttpService instance;
Private OkHttpClient client;

Private OkhttpService (){
Client = new OkHttpClient (); // get an OkthhpClient instance
}
Public static OkhttpService getInstance (){
Return instance = null? Instance = new OkhttpService (): instance;
}

// Batch encapsulate the Magic Box (post submits json data)
Note: RequestBody body = RequestBody. create (JSON, json); // The json data is body
Request is an access Request in OkHttp, and Builder is a helper class. Response is the Response in 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); // serialize boxProd to json
Request request = new Request. Builder ()
. Url (route)
. Post (RequestBody. create (JSON, json) // use the post method of the Request to submit the Request body RequestBody
. Build ();
Response response = client.newcall(requestcmd.exe cute ();
Boolean isOk = response. isSuccessful ();
Return response. body (). string (); // response. body () returns the ResponseBody class.
}

// Submit the box at the outlet for receiving and mounting
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 responseappsclient.newcall(requestcmd.exe cute ();
Boolean isOk = response. isSuccessful ();
Return response. body (). string ();
}
}
Note: The preceding two methods must be accessed at the front-end. The returned results must be prompted to the front-end (States (return status: success or failure), Description (result Description), and Data (Data) must be provided in the interface)

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

2. Summary of official documents
(1) Configuration
Import Jar package
Import = meaven through Build Mode

(2) Basic Requirements
Request
Response

(3) Basic use
-- Http GET

OkHtttpClient client = new okHtttpClient ();

String run (String url) throws IOException {
Request request = new Request. Builder (). url (url). build ();
Response response = client.newcall(requestcmd.exe cute ();
If (response. isSuccessful ()){
Return response. body (). string ();
} Else {
Throw new IOException ("Unexpected code" + response );
}
}
Note: Request is the access Request in OkHttp, Builder is the helper class, and Response is the Response in OkHttp

-- Http POST

"POST submit Json data

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(requestcmd.exe cute ();
If (response. isSuccessful ())
{
Return response. body (). string ();
} Else
{
Throw new IOException ("Unexpected code" + response );
}
}
Note: Use the post method of the Request to submit the Request body RequestBody.

"POST submits key-value pairs
OkHttp can also transmit the key-value pair data to the server through the POST method.

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(requestcmd.exe cute ();
If (response. isSuccessful ())
{
Return response. body (). string ();
} Else {
Throw new IOException ("Unexpected code" + response );
}
}

(3) Case studies

Layout file:
<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 = "wooyun Get request"/>

<Button android: id = "@ + id/bt_post"
Android: layout_width = "wrap_content"
Android: layout_height = "wrap_content"
Android: text = "wooyun Post request"/>

LinearLayout>

<TextView android: id = "@ + id/TV _show"
Android: layout_width = "match_parent"
Android: layout_height = "wrap_content"/>

LinearLayout>

Java code:
Because android itself does not allow network request operations in the UI thread, we write a thread to complete network operations.

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(requestcmd.exe cute ();
If (response. isSuccessful ()){
Log. I ("WY", "print GET response data:" + 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(requestcmd.exe cute ();
If (response. isSuccessful ()){
Log. I ("WY", "Print POST response Data:" + response. body (). string ());
} Else {
Throw new IOException ("Unexpected code" + response );
}
} Catch (IOException e ){
E. printStackTrace ();
}
}
}). Start ();
}
}

The following is a brief description:
Synchronize Get

Download an object, print its response header, and print the response body in string format.
The string () method of the response body is very convenient and efficient for small documents. However, if the response body is too large (more than 1 MB), avoid adapting to the string () method because it will load the entire document into the memory. For response bodies larger than 1 MB, the stream should be used to process the body.

Asynchronous Get

Download files in a work thread and call back the Callback interface when the response is readable. The current thread is blocked when the response is read. OkHttp currently does not provide asynchronous APIs to receive response bodies.

Extract Response Header

The typical HTTP header is like a Map

Submit String in Post Mode

Use http post to submit a request to the service. In this example, a markdown document is submitted to the web service to render markdown in HTML mode. Because the entire request body is in memory, avoid using this api to submit large files (larger than 1 MB ).

 

To be continued .........

Part from http://m.2cto.com/net/201605/505364.html

 





 



 

                     

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.