Android网络请求(HTTP)

整体思路从该博客中学习。


这里我们只从HTTP协议请求网络数据时,学习相关东西。

在HTTP请求时,在Android支持的两大类HttpURLConnection和HttpClient来请求HTTP数据,但是在Android6.0直接删除了HttpClient库。然而在使用HttpURLConnection中相对复杂,所以之后的第三方网络请求框架都是从这两个库中得来的。

AndroidStudio中要使用HttpClient需要添加如下代码在app的build.gradle中:

Android{

useLibrary 'org.apache.http.legacy'

    }

编译后就可以使用HttpClient类了。

1.HttpClient


	HttpClient httpCient = new DefaultHttpClient();
首先是初始化,这种方式就是用默认的设置,当然,你也可以自己设置请求时间等。
	HttpParams mDefaultHttpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(mDefaultHttpParams, 15000);
        // 设置请求超时
        HttpConnectionParams.setTcpNoDelay(mDefaultHttpParams, true);
        HttpProtocolParams.setVersion(mDefaultHttpParams, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(mDefaultHttpParams, HTTP.UTF_8);
        // 持续握手
        HttpProtocolParams.setUseExpectContinue(mDefaultHttpParams, true);
        
	HttpClient mHttpClient = new DefaultHttpClient(mDefaultHttpParams);
 
 这里我们自己设置了连接时间,请求时间等。 
 

这是我们的主过程:HttpPost –> HttpClient –> HttpResponse


然后我们需要确认请求方式,GET or POST

        HttpGet mHttpGet = new HttpGet(url);
        HttpPost mHttpPost = new HttpPost(url);

你也可以在此添加需要的相应头。


对于我们要传入Json数据时,可以使用StringEntity类。存入json字符串和他的编码格式就行了。

	StringEntity entity = new StringEntity("json", "utf-8");
        mHttpPost.setEntity(entity);
当然该会有list集合作为参数传递:

        List<NameValuePair> postParams = new ArrayList<>();
        postParams.add(new BasicNameValuePair("userName", "123"));
        postParams.add(new BasicNameValuePair("userpw", "456"));
        mHttpPost.setEntity(new UrlEncodedFormEntity(postParams));
以上就是对相应参数传递的方法。

最后就是请求网络数据,并接收返回值:

        HttpResponse mHttpResponse = mHttpClient.execute(mHttpGet);
        if (mHttpResponse.getStatusLine().getStatusCode() == 200) {
            HttpEntity mEntity = mHttpResponse.getEntity();
            
        }
所有的数据都在mEntity中。

2.HttpURLConnection

同上,我们首先要初始化连接参数:

然后是确认我们是POST or GET请求方式:

            URL mUrl = new URL(url);
            mHttpURLConnection = (HttpURLConnection) mUrl.openConnection();
            mHttpURLConnection.setConnectTimeout(15000);
            mHttpURLConnection.setReadTimeout(15000);
            mHttpURLConnection.setRequestMethod("GET");
            mHttpURLConnection.setRequestMethod("POST");
	    mHttpURLConnection.connect();

在传参时可以用其getOutputStream()方法来写入参数

在读取数据时,我们可以使用流的方式读取getInputStream()方法读取数据

在结束之后,一定要关闭所以的流和连接。


猜你喜欢

转载自blog.csdn.net/github_34437042/article/details/61192143