1. 程式人生 > >16.android兩種post請求,Headers方式和JSONObject方式

16.android兩種post請求,Headers方式和JSONObject方式

//首先在AndroidManifest.xml裡寫入網路許可權:

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

 //第二步寫ml佈局,一個Button,一個Text

<Button
    android:id="@+id/mButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!"
    />

<TextView
    android:id="@+id/mText"
    android:text="aaa"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

Headers方式:

 //第一步寫個Request介面:

//請求方式post動態請求
public interface Request {
        @Headers({"Content-Type:application/json"})//需要新增頭
        @POST
        Observable<ResponseBody> postinfo(@Url String url, @Body RequestBody info);
}

//第二步寫了個Retrofit的單例模式Singleton類:

//Retrofit單例模式---懶漢式
public class Singleton {
    private static Singleton singleton;
    private Retrofit retrofit;

    private Singleton(){
        retrofit=new Retrofit.Builder()
                .baseUrl("http://39.107.70.72:9090/workos/")
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }

    public static Singleton getSingleton(){
        if (singleton==null){
            synchronized (Singleton.class){
                singleton=new Singleton();
            }
        }
        return singleton;
    }

    public Retrofit getRetrofit() {
        return retrofit;
    }
}

//需要匯入Retrofit的依賴:

//Retrofit+RxJava依賴
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.0.2'
implementation 'io.reactivex.rxjava2:rxjava:2.1.12'
implementation 'io.reactivex:rxandroid:1.0.1'
implementation 'com.squareup.retrofit2:adapter-rxjava:2.0.2'

//第三步寫個Bean類:

//Bean類兩個欄位賬號和密碼
public class Bean {

    /**
     * user_name : 9371440
     * user_pwd : 123
     */

    private String user_name;
    private String user_pwd;

    public String getUser_name() {
        return user_name;
    }

    public void setUser_name(String user_name) {
        this.user_name = user_name;
    }

    public String getUser_pwd() {
        return user_pwd;
    }

    public void setUser_pwd(String user_pwd) {
        this.user_pwd = user_pwd;
    }
}

//第三步 Activity裡寫個方法,Button按鈕呼叫,Text顯示請求結果:

    //發起網路請求
    public void Request() {
        Retrofit retrofit = Singleton.getSingleton().getRetrofit();
        Request request = retrofit.create(Request.class);
        //new 出這個bean類
        Bean bean = new Bean();
//新增手機號,和預設登入型別0
        bean.setUser_name("9371440");
        bean.setUser_pwd("123");
        //new gson,通過gson.tojson把bean類轉成string字串。
        Gson gson = new Gson();
        String s = gson.toJson(bean);
        //把字串新增到requestBody裡,格式是utf-8
        RequestBody requestBody = RequestBody.create(MediaType.parse("charset=utf-8"), s);

//然後請求這個requestBody
        request.postinfo("user/login", requestBody)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResponseBody>() {
                    @Override
                    public void onCompleted() {

                    }

                    //失敗的方法
                    @Override
                    public void onError(Throwable e) {
                        Toast.makeText(MainActivity.this, e.getMessage() + "", Toast.LENGTH_SHORT).show();
                    }

                    //成功的方法
                    @Override
                    public void onNext(ResponseBody responseBody) {
                        try {
                            String string = responseBody.string();
                            Log.e("TAG", string);
                            Toast.makeText(MainActivity.this, string + "", Toast.LENGTH_SHORT).show();
                            //這個Text顯示請求結果
                            mText.setText(string);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }

                    }
                });
    }

//初始化控制元件,Button按鈕呼叫:

private void initView() {
    mButton = (Button) findViewById(R.id.mButton);
    mText = (TextView) findViewById(R.id.mText);

    mButton.setOnClickListener(this);
}

//Button按鈕呼叫
@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.mButton:
            Request();
            break;
    }
}

//-------------------------------------------------第一種Headers請求方式完畢----------------------------------------------------

//第二種JSONObject方式請求資料:

//第一步 寫個JsonPost()方法,用來發起網路請求,傳遞兩個引數,一個是網路地址,一個是提交的Json串。

    //發起網路請求,獲得URL,獲得Json串
    public  String JsonPost(final String path, final JSONObject json) {

        BufferedReader in = null;
        String result = "";
        OutputStream os = null;
        try {
            URL url = new URL(path);
// 然後我們使用httpPost的方式把lientKey封裝成Json資料的形式傳遞給伺服器
// 在這裡呢我們要封裝的時這樣的資料
// 我們把JSON資料轉換成String型別使用輸出流向伺服器寫
            String content = String.valueOf(json);
// 現在呢我們已經封裝好了資料,接著呢我們要把封裝好的資料傳遞過去
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
// 設定允許輸出
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
// 設定User-Agent: Fiddler
            conn.setRequestProperty("ser-Agent", "Fiddler");
// 設定contentType
            conn.setRequestProperty("Content-Type", "application/json");
            os = conn.getOutputStream();
            os.write(content.getBytes());
            os.flush();
// 定義BufferedReader輸入流來讀取URL的響應
// Log.i("-----send", "end");

            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            if (conn.getResponseCode() == 200) {
                while ((line = in.readLine()) != null) {
                    result += line;
                }
            }
        } catch (SocketTimeoutException e) {
// Log.i("錯誤", "連線時間超時");
            e.printStackTrace();
            return "錯誤";
        } catch (MalformedURLException e) {
// Log.i("錯誤", "jdkfa");
            e.printStackTrace();
            return "錯誤";
        } catch (ProtocolException e) {
// Log.i("錯誤", "jdkfa");
            e.printStackTrace();
            return "錯誤";
        } catch (IOException e) {
// Log.i("錯誤", "jdkfa");
            e.printStackTrace();
            return "錯誤";
        }// 使用finally塊來關閉輸出流、輸入流
        finally {
            try {
                if (os != null) {
                    os.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

//第二步寫個getjsonData()方法,把引數變為Json串。

//提交引數,賬號和密碼,變為Json串
public JSONObject getjsonData() {

    JSONObject js=new JSONObject();

    try {

        js.put("user_name", "9371440");

        js.put("user_pwd", "123");


    } catch (JSONException e) {

        // TODO Auto-generated catch block

        e.printStackTrace();

    }

    return js;

}

//第三步 Button按鈕呼叫JsonPost方法,並傳遞引數,發起網路請求,Text顯示。(注意切換執行緒)

private void initView() {
    mButton = (Button) findViewById(R.id.mButton);
    mText = (TextView) findViewById(R.id.mText);

    mButton.setOnClickListener(this);
}

//Button按鈕呼叫
@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.mButton:
            //切換為子執行緒發起網路請求,主執行緒不能做網路請求
            new Thread(new Runnable() {
                @Override
                public void run() {
                    final String s = JsonPost("http://39.107.70.72:9090/workos/user/login", getjsonData());
                    //切換為主執行緒更新UI,Text顯示
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mText.setText(s);
                            Toast.makeText(MainActivity.this, "" + s, Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }).start();
            break;
    }
}

//-----------------------------------------------------------------------完------------------------------------------------------------------------