HttpURLConnection使用方法

一.详解

任何网络连接都需要经过socket才能连接,HttpURLConnection不需要设置socket,所以,HttpURLConnection并不是底层的连接,而是在底层连接上的一个请求。这就是为什么HttpURLConneciton只是一个抽象类,自身不能被实例化的原因。HttpURLConnection只能通过URL.openConnection()方法创建具体的实例。

二.代码实现

1.在MyAsyncTask中

package com.example.zhouyf.demo06;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

/**
 * Created by Zhouyf on 2017/9/7.
 */

public class MyAsyncTask extends AsyncTask{
    private Context context;
    private ListView listView;
    private String path;
    private String type;
    private DataBean bean;

    public MyAsyncTask(Context context, ListView listView, String path, String type) {
        this.context = context;
        this.listView = listView;
        this.path = path;
        this.type = type;
    }

    public void getData(String mpath,String mtype){
        try {
            URL url = new URL(mpath);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod(mtype);
            connection.setReadTimeout(5000);
            connection.setConnectTimeout(5000);

            connection.setDoOutput(true);
            String mptname = "key=8d6e3228d25298f13af4fc40ce6c9679&num=10";
            connection.getOutputStream().write(mptname.getBytes());

            int responseCode = connection.getResponseCode();
            if (responseCode==200){
                InputStream inputStream = connection.getInputStream();
                String s = readText(inputStream,"utf-8");
                Gson gson = new Gson();
                bean = gson.fromJson(s, DataBean.class);

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public String readText(InputStream inputStream,String charset){
        try {
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream,charset);
            BufferedReader buffer = new BufferedReader(inputStreamReader);
            String s=null;
            StringBuilder builder = new StringBuilder();
            while ((s = buffer.readLine())!=null){
                builder.append(s);
            }
            buffer.close();
            inputStreamReader.close();
            return builder.toString();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected String doInBackground(String... strings) {
        getData(path,type);
        return null;
    }

    @Override
    protected void onPostExecute(String s) {
        List newslist = bean.getNewslist();
        MyAdapter adapter = new MyAdapter(context, newslist);
        listView.setAdapter(adapter);
        super.onPostExecute(s);
    }
}
2.在MainActivity

package com.example.zhouyf.demo06;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;

public class MainActivity extends AppCompatActivity {

    private ListView lv;
    String path = "https://api.tianapi.com/wxnew/?key=8d6e3228d25298f13af4fc40ce6c9679&num=10";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lv = (ListView) findViewById(R.id.lv);
        initData(Url.mPath);
    }
    public void initData(String url){
        MyAsyncTask myAsyncTask = new MyAsyncTask(MainActivity.this, lv, url, "GET");
        myAsyncTask.execute();
    }
}

以上只是部分代码,请斟酌使用












你可能感兴趣的:(HttpURLConnection使用方法)