请求方式

来源:互联网 发布:乔丹个赛季数据 编辑:程序博客网 时间:2024/06/05 17:55
package com.example.chenweifei20171202.utils;import android.os.AsyncTask;import org.apache.http.HttpEntity;import org.apache.http.HttpResponse;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.util.EntityUtils;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import java.net.URLConnection;/** * Created by DELL on 2017/12/2. */public class MyTask extends AsyncTask<String,Void,String>{    private ICallBack iCallBack;    public MyTask(ICallBack iCallBack) {        this.iCallBack = iCallBack;    }    @Override    protected String doInBackground(String... strings) {        String Str="";        String count = strings[1];        if ("1".equals(count)){            try {                URL url = new URL(strings[0]);                HttpURLConnection conn = (HttpURLConnection) url.openConnection();                if(conn.getResponseCode()==200){                    InputStream is = conn.getInputStream();                    BufferedReader br=new BufferedReader(new InputStreamReader(is));                    StringBuilder sb = new StringBuilder();                    String temp="";                    while((temp=br.readLine())!=null){                        sb.append(temp);                    }                    Str=sb.toString();                }            } catch (MalformedURLException e) {                e.printStackTrace();            } catch (IOException e) {                e.printStackTrace();            }        }else{            //获取httpclient对象            DefaultHttpClient defaultHttpClient = new DefaultHttpClient();            //准备一个get请求            HttpPost httpPost = new HttpPost(strings[0]);            try {                //得到服务器返回的数据;                HttpResponse response = defaultHttpClient.execute(httpPost);                //得到状态码                int statusCode = response.getStatusLine().getStatusCode();                if(statusCode ==200){                    //entiry 里面封装的数据;                    HttpEntity entity = response.getEntity();                    Str = EntityUtils.toString(entity);                }            } catch (IOException e) {                e.printStackTrace();            }        }        return Str;    }    @Override    protected void onPostExecute(String s) {        super.onPostExecute(s);        iCallBack.UpDataUIThread(s);    }    public  interface ICallBack{        void UpDataUIThread(String jsonstr);    }}