网络请求:HttpURLConnection、HttpClient、HttpUtils、Volley

来源:互联网 发布:顶尖文案网 知乎 编辑:程序博客网 时间:2024/05/21 13:07

下面介绍网络请求获取json字符串的四种方法。
其中会用到的jar包
xUtils-2.6.14.jar:(http://pan.baidu.com/s/1gfHYrkR)
volley.jar:(http://pan.baidu.com/s/1boXzsi7)

  • HttpURLConnection:原生的,直接用即可。
  • HttpClient:1.在使用eclipse时上要加上jar包;
    httpclient-android-4.3.5.jar:http://pan.baidu.com/s/1dFiQ7TJ
    httpclient-android-4.3.5-sources.jar:http://pan.baidu.com/s/1gfPzRer
    2.使用AndroidStudio时要在build.gradle文件中添加:
    android{
    useLibrary ‘org.apache.http.legacy’
    }
  • HttpUtils为XUtils框架中的其中一个模块
    xUtils-2.6.14.jar:http://pan.baidu.com/s/1i5fuAgd
  • Volley.jar:http://pan.baidu.com/s/1slGrZmX

具体实现上代码

package com.example.xhm.httputils;import android.content.Context;import android.util.Log;import com.android.volley.RequestQueue;import com.android.volley.Response;import com.android.volley.VolleyError;import com.android.volley.toolbox.JsonObjectRequest;import com.android.volley.toolbox.Volley;import com.lidroid.xutils.HttpUtils;import com.lidroid.xutils.exception.HttpException;import com.lidroid.xutils.http.ResponseInfo;import com.lidroid.xutils.http.callback.RequestCallBack;import com.lidroid.xutils.http.client.HttpRequest;import org.apache.http.HttpResponse;import org.apache.http.HttpStatus;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpGet;import org.apache.http.impl.client.DefaultHttpClient;import org.json.JSONObject;import java.io.BufferedInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;import java.io.InputStream;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.ProtocolException;import java.net.URL;import java.util.Objects;/** * Created by xhm on 2017/3/2. */public class HttpUtil {    private static final String TAG=HttpUtil.class.getSimpleName();    private Context context;    public HttpUtil(Context context){        this.context=context;    }    //1.原始url    public  void urlHttp(final String path){        new Thread(new Runnable() {            @Override            public void run() {                try {                    URL url = new URL(path);                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();                    conn.setRequestMethod("GET");                    conn.setUseCaches(false);                    conn.setDoOutput(false);                    conn.setDoInput(true);                    int responseCode = conn.getResponseCode();                    if (responseCode == 200) {                        InputStream is = conn.getInputStream();                        String json = inputStream2String(is);                        Log.e(TAG,"HttpUrlConn 获取的信息为:"+json);                    }                } catch (MalformedURLException e) {                    e.printStackTrace();                } catch (ProtocolException e) {                    e.printStackTrace();                } catch (IOException e) {                    e.printStackTrace();                }            }        }).start();    }    private  String inputStream2String(InputStream is) throws IOException {        String json;        BufferedInputStream bis = new BufferedInputStream(is);        ByteArrayOutputStream baos = new ByteArrayOutputStream();        byte[] buffer = new byte[64];        int leng = -1;        while ((leng = bis.read(buffer)) != -1) {            baos.write(buffer, 0, leng);        }        bis.close();        is.close();        baos.flush();        json = new String(baos.toByteArray());        baos.close();        return json;    }    //2.httpClient    public void HttpClientUtil(final String path){        new Thread(new Runnable() {            @Override            public void run() {                try {                    //得到HttpClient对象                    HttpClient getClient = new DefaultHttpClient();                    //得到HttpGet对象                    HttpGet request = new HttpGet(path);                    //客户端使用GET方式执行请教,获得服务器端的回应response                    HttpResponse response = getClient.execute(request);                    //判断请求是否成功                    if(response.getStatusLine().getStatusCode()== HttpStatus.SC_OK){                        //获得输入流                        InputStream  inStrem = response.getEntity().getContent();                        String json=inputStream2String(inStrem);                        Log.e(TAG,"HttpClient 获取的信息为:"+json);                    }                } catch (Exception e) {                    e.printStackTrace();                }            }        }        ).start();    }    //3.Xutil    public void Xutils(String path){        HttpUtils httpUtils=new HttpUtils();        httpUtils.send(HttpRequest.HttpMethod.GET, path, new RequestCallBack<String>() {            @Override            public void onLoading(long total, long current, boolean isUploading) {                super.onLoading(total, current, isUploading);                Log.e(TAG,"进行中...");            }            @Override            public void onSuccess(ResponseInfo<String> responseInfo) {                String json=responseInfo.result;                Log.e(TAG,"Xutil 获取的信息为:"+json);                Log.e(TAG,"成功...");            }            @Override            public void onFailure(HttpException e, String s) {                Log.e(TAG,"失败...");            }        });    }    //3.Volley    public void VolleyUtil(String path){        RequestQueue mQueue = Volley.newRequestQueue(context);        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(path, null,                new Response.Listener<JSONObject>() {                    @Override                    public void onResponse(JSONObject response) {                        String json= response.toString();                       Log.e(TAG,"Volley 获取的信息为:"+json);                    }                }, new Response.ErrorListener() {            @Override            public void onErrorResponse(VolleyError error) {                Log.e(TAG, "err="+error.getMessage(), error);            }        });        mQueue.add(jsonObjectRequest);    }}

最后不要忘记添加权限:

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

若需将获取的信息传递mainThread里,可参考:http://blog.csdn.net/xinyonghuyiersan/article/details/58162693

源码下载:http://pan.baidu.com/s/1bo9IK3t

0 0
原创粉丝点击