HTTP通信

image.png

image.png

GET與POST的區(qū)別
image.png

http:上傳:
image.png

Http:下載
image.png

image.png

HttpURLConnection使用詳解:
https://blog.csdn.net/fightingXia/article/details/71775516

如何使用HTTPURLConnetion 訪問接口:
https://blog.csdn.net/huaduotongtong/article/details/51076253

在Android開發(fā)中常常需要訪問接口來獲取數(shù)據(jù),這個(gè)時(shí)候可以使用HttpURLConnection來連接服務(wù)器并獲取返回字符串。
這樣,該函數(shù)返回回來的字符串就是接口返回的字符串,如果該字符串為json格式的,那么按照json去解析便可以了。
GET請(qǐng)求:
布局:
xml
···
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.lenovo.test_01.MainActivity"
>

<Button
    android:id="@+id/button"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Get"
    />

<Button
    android:id="@+id/button2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="POST" />

<Button
    android:id="@+id/button3"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Button" />

<TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="TextView" />

</LinearLayout>

···
*****MainActivity:**********************
···
package com.example.lenovo.test_01;

import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
Button btGet,btPost ,btDownLoad;
TextView tx;
//安卓4.0之后規(guī)定聯(lián)網(wǎng)的操作必須在子線程中完成
//主線程中聯(lián)網(wǎng)報(bào)錯(cuò):android.os.NetworkOnMainThreadException

//創(chuàng)建Hander
Handler handler =new Handler(){
    @Override
    public void handleMessage(Message msg) {
        if (msg.what==0x111){
            tx.setText(msg.obj.toString());
        }
        if(msg.what==0x112){
            tx.setText(msg.obj.toString());
        }
    }
};
//創(chuàng)建聯(lián)網(wǎng)對(duì)象
HttpURLConnection con;
//地址對(duì)象
URL url;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
     init();
}
void init() {
    btGet = (Button) findViewById(R.id.button);
    btGet.setOnClickListener(this);
    btPost = (Button) findViewById(R.id.button2);
    btPost.setOnClickListener(this);
    btDownLoad = (Button) findViewById(R.id.button3);
    btDownLoad.setOnClickListener(this);
    tx = (TextView) findViewById(R.id.textView);
}

void getMothed(){
new Thread(){
public void run(){
//封裝網(wǎng)絡(luò)地址
//網(wǎng)址跟數(shù)據(jù)之間應(yīng)?關(guān)聯(lián)
try {

            url =new URL("http://op.juhe.cn/onebox/movie/video?" +
                    "dtype=&q="+"復(fù)仇者聯(lián)盟3: 無限戰(zhàn)爭(zhēng)"+"&key=d6c3131e11deddfd0bef9deadfa05334");
            //創(chuàng)建連接對(duì)象
            con= (HttpURLConnection) url.openConnection();

// 設(shè)置連接對(duì)象屬性
con.setDoOutput(true);//允許發(fā)送 接收數(shù)據(jù)
con.setDoInput(true);
//設(shè)置請(qǐng)求方式
con.setRequestMethod("GET");
//設(shè)置請(qǐng)求超時(shí)和接收超時(shí)
con.setConnectTimeout(10000);
con.setReadTimeout(10000);

            //開始連接
            con.connect();
            //讀取數(shù)據(jù) 獲取輸入流對(duì)象接收數(shù)據(jù)
            InputStream is=con.getInputStream();
            if (con.getResponseCode()==200){//獲得的請(qǐng)求碼 200 代表請(qǐng)求成功
                ByteArrayOutputStream bos=  new ByteArrayOutputStream();
                int length=-1;//標(biāo)記最后一次搬運(yùn)的長(zhǎng)度
                byte buffer[] =new byte[1024];
                while ((length=is.read(buffer))!=-1){
                    bos.write(buffer,0,length);
                    bos.flush();
                }
                is.close();
                bos.close();

                          Message message=handler.obtainMessage();
                          message.obj=bos.toString();
                          message.what=0x111;
                          handler.sendMessage(message);


            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}.start();

}
@Override
public void onClick(View view) {
switch (view.getId()){
//聯(lián)網(wǎng) 4.0以后不允許主線程聯(lián)網(wǎng)
case R.id.button:
//get請(qǐng)求 將地址和請(qǐng)求數(shù)據(jù)綁在一起 安全系數(shù)低 請(qǐng)求數(shù)據(jù)不能大于2kb
getMothed();

           break;
       case R.id.button2:
           //post請(qǐng)求 地址對(duì)象中不需要數(shù)據(jù)
           getPost();

           break;
       case R.id.button3:
           getDownLoad();  //從服務(wù)器下載文件
           break;
   }
}
//從服務(wù)器下載文件
void  getDownLoad(){
    new Thread() {
        public void run() {
            try {
                //1.通過URL對(duì)象封裝網(wǎng)址
                url = new URL("http://169.254.195.164:8080/a3.jpg");
                //2.通過URL對(duì)象獲取連接對(duì)象
                con = (HttpURLConnection) url.openConnection();

// 3. 設(shè)置連接對(duì)象屬性
con.setDoOutput(true);//允許上傳
con.setDoInput(true);//允許下載
con.setRequestMethod("POST"); //設(shè)置請(qǐng)求方式
//設(shè)置請(qǐng)求超時(shí)和讀取超時(shí)
con.setConnectTimeout(10000);
con.setReadTimeout(10000);
con.connect();
//4.判斷是否請(qǐng)求成功
if (con.getResponseCode() == 200) {//獲得的請(qǐng)求碼 200 代表請(qǐng)求成功
//讀取數(shù)據(jù) 獲取輸入流對(duì)象接收數(shù)據(jù)
InputStream is = con.getInputStream();
//判斷SD卡是否存在
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
File file =new File(Environment.getExternalStorageDirectory()+"/my1710.jpg");
FileOutputStream fos=new FileOutputStream(file);
byte buffer[]=new byte[1024];
int length=-1;
while ((length = is.read(buffer)) != -1) {
fos.write(buffer, 0, length);
fos.flush();

                        }
                        is.close();
                        fos.close();
                    }else {

                      handler.sendEmptyMessage(2);

                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }.start();

}
//post獲取

void getPost(){
new Thread() {
public void run() {
//封裝網(wǎng)絡(luò)地址
//網(wǎng)址跟數(shù)據(jù)之間應(yīng)?關(guān)聯(lián)
try {
//1.通過URL對(duì)象封裝網(wǎng)址
url = new URL("http://op.juhe.cn/onebox/movie/video");
//
//2.創(chuàng)建連接對(duì)象
con = (HttpURLConnection) url.openConnection();
// 3. 設(shè)置連接對(duì)象屬性
con.setDoOutput(true);//允許上傳
con.setDoInput(true);//允許下載
con.setRequestMethod("POST"); //設(shè)置請(qǐng)求方式
//設(shè)置請(qǐng)求超時(shí)和讀取超時(shí)
con.setConnectTimeout(10000);
con.setReadTimeout(10000);
con.connect();
//4.發(fā)送數(shù)據(jù)
OutputStream os=con.getOutputStream();
byte data[]=( "dtype=&q=" + "復(fù)仇者聯(lián)盟3: 無限戰(zhàn)爭(zhēng)" + "&key=d6c3131e11deddfd0bef9deadfa05334").getBytes("UTF-8");
os.write(data,0,data.length);
os.flush();
os.close();
//5.判斷是否請(qǐng)求成功
if (con.getResponseCode() == 200) {//獲得的請(qǐng)求碼 200 代表請(qǐng)求成功
//讀取數(shù)據(jù) 獲取輸入流對(duì)象接收數(shù)據(jù)
InputStream is = con.getInputStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int length = -1;//標(biāo)記最后一次搬運(yùn)的長(zhǎng)度
byte buffer[] = new byte[1024];
while ((length = is.read(buffer)) != -1) {
bos.write(buffer, 0, length);
bos.flush();

                  }
                  is.close();
                  bos.close();

                          Message message=handler.obtainMessage();
                          message.obj=bos.toString();
                          message.what=0x112;
                          handler.sendMessage(message);


              }
          } catch (Exception e) {
              e.printStackTrace();
          }
      }
  }.start();

}

}

···
效果圖:

QQ圖片20180711161552.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容