HttpUrlConnection

1.GET和POST方式有什么区别

GET请求的数据是放在HTTP包头中的,也就是URL之后,而Post是把提交的数据放在HTTP正文中的。

GET提交的数据比较少,最多1024B,因为GET数据是附在URL之后的,而URL则会受到不同环境的限制的,而POST可以传送更多的数据

2.String/StringBuffer/StringBuilder什么区别

String:不可变字符序列
StringBuffer:可变字符序列,效率低,线程安全
StringBuilder:可变字符序列,效率高,线程不安全

3.HttpUrlConnection请求网络数据实例

布局文件:

<?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"
    tools:context="com.example.administrator.myapplication6.InternetActivity">
    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width= "match_parent"
        android:layout_height= "match_parent"
        android:orientation="vertical" >

        <Button
            android:id= "@+id/btn_send_request"
            android:layout_width= "match_parent"
            android:layout_height= "wrap_content"
            android:text="请求网络" />

        <ScrollView
            android:layout_width= "match_parent"
            android:layout_height= "match_parent" >

            <TextView
                android:id= "@+id/tv_show_content"
                android:layout_width= "wrap_content"
                android:layout_height= "wrap_content" />
        </ScrollView >

    </LinearLayout>
</LinearLayout>

MainActivity.java

package com.example.administrator.myapplication6;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

public class InternetActivity extends AppCompatActivity implements OnClickListener {
    private Button btnSendRequest;
    private TextView tvShowContent;
    private static final String httpUrl = "http://www.imooc.com/api/teacher?type=4&num=40";
    public static final int SHOW_RESPONSE = 0;




    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SHOW_RESPONSE:
                    String result = (String) msg.obj;
                    tvShowContent.setText(result);
                    break;
            }
        }

        ;
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_internet);
        btnSendRequest=(Button) findViewById(R.id.btn_send_request );
        tvShowContent=(TextView) findViewById(R.id.tv_show_content );

        btnSendRequest.setOnClickListener(this);

    }
    public void onClick(View v) {
        if(v.getId()==R.id. btn_send_request){
            httpUrlConnection_get();
        }
    }

    private void httpUrlConnection_get() {
        new Thread( new Runnable() {

            @Override
            public void run() {

                InputStreamReader in= null;
                HttpURLConnection httpUrlConnection= null;
                try {

                    URL url= new URL("http://www.baidu.com" );
                    httpUrlConnection = (HttpURLConnection) url.openConnection();
                    httpUrlConnection.setRequestMethod( "GET"); //设置请求方法
                    httpUrlConnection.setConnectTimeout(8000); //设置链接超时的时间
                    httpUrlConnection.setReadTimeout(8000);
                    httpUrlConnection.setDoInput( true); //允许输入流,即允许下载
                    httpUrlConnection.setDoOutput( true); //允许输出流,即允许上传
                    httpUrlConnection.setUseCaches( false); //设置是否使用缓存

                    httpUrlConnection.connect();
                    InputStream inputStream=httpUrlConnection.getInputStream();
                    in= new InputStreamReader(inputStream);
                    BufferedReader bf= new BufferedReader(in);
                    StringBuffer sb= new StringBuffer();
                    String inputLine= null;

                    while((inputLine=bf.readLine())!= null){
                        sb.append(inputLine);
                    }

                    Message message= new Message();
                    message. what= SHOW_RESPONSE;
                    message. obj=sb.toString();
                    handler.sendMessage(message);

                } catch (Exception e) {
                    e.printStackTrace();
                } finally{
                    if(httpUrlConnection!= null){
                        httpUrlConnection.disconnect();
                    }
                }
            }
        }).start();

    }

}

4..HttpUrlConnection请求网络图片实例

布局文件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    xmlns:tools="http://schemas.android.com/tools"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent"  
    tools:context="${relativePackage}.${activityClass}" >  

    <Button  
        android:id="@+id/btn1"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:text="获取图片" />  
    <ImageView   
        android:id="@+id/img1"  
        android:layout_width="200dp"  
        android:layout_height="200dp"  
        android:layout_below="@id/btn1"  
        android:src="@drawable/ic_launcher"  
        />  

</RelativeLayout>  

MainActivity.java

package com.example.getremoteimg;  

import java.io.IOException;  
import java.io.InputStream;  
import java.net.HttpURLConnection;  
import java.net.URL;  

import android.app.Activity;  
import android.graphics.Bitmap;  
import android.graphics.BitmapFactory;  
import android.os.AsyncTask;  
import android.os.Bundle;  
import android.view.View;  
import android.view.View.OnClickListener;  
import android.widget.Button;  
import android.widget.ImageView;  

public class MainActivity extends Activity {  

    private Button btn1;  
    private ImageView img1;  

    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
        btn1 = (Button) findViewById(R.id.btn1);  
        img1 = (ImageView) findViewById(R.id.img1);  
        btn1.setOnClickListener(new OnClickListener() {  

            @Override  
            public void onClick(View v) {  
                String imgUrl = "http://p1.meituan.net/deal/a5c0180d48419fe09f8edb0f267a7e7767069.jpg";  
                new DownImgAsyncTask().execute(imgUrl);  
            }  
        });  
    }  

    private Bitmap getImageBitmap(String url) {  
        URL imgurl = null;  
        Bitmap bitmap = null;  

        HttpURLConnection urlConnection;  
        try {  
            imgurl = new URL(url);  
            urlConnection = (HttpURLConnection)   
                    imgurl.openConnection();  
            urlConnection.setRequestMethod("GET");   
            urlConnection.connect();  
            InputStream is = urlConnection.getInputStream();  
            bitmap = BitmapFactory.decodeStream(is);  
            is.close();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        return bitmap;  
    }  

    class DownImgAsyncTask extends AsyncTask<String, Void, Bitmap>{  


        @Override  
        protected void onPreExecute() {  
            super.onPreExecute();  
            img1.setImageBitmap(null);  
        }  

        @Override  
        protected void onPostExecute(Bitmap result) {  
            super.onPostExecute(result);  
            if (result != null) {  
                img1.setImageBitmap(result);  
            }  
        }  

        @Override  
        protected Bitmap doInBackground(String... params) {  
            Bitmap b = getImageBitmap(params[0]);  
            return b;  
        }  

    }  

}  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值