Android使用OkHttpClient进行简单的Http请求

这篇博客主要是介绍怎么简单使用OkHttpClient访问Url进行简单的Http请求。

第一步,在Android工程中添加依赖:

compile 'com.squareup.okhttp3:okhttp:3.7.0'

这里以okhttp3为例子,在build.gradle(app)下的dependencies标签下添加依赖:

第二步,代码实现:

可以新建一个类用来练习,这里我随便建了个类

代码如下:

package com.example.Web;

import android.util.Log;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;



public class WebDataReceive {

	private void ReceiveDataFromWeb() {
		OkHttpClient client = new OkHttpClient();
		//这里为了方便和代码可读性分开三行
		Request request = new Request.Builder()
				.url("http://www.baidu.com")		//双引号内需要填入你需要访问的url地址
				.get()		//默认就是GET请求,可以不写
				.build();
		Call call = client.newCall(request);
		call.enqueue(new Callback() {
			@Override
			public void onFailure(Call call, IOException e) {
				//如果出错,打个Log方便查看日志
				Log.e("onFailure: ", String.valueOf(e));
			}

			@Override
			public void onResponse(Call call, Response response) throws IOException {
				//一般会得到Json数据,这时候就要用Json解析的一系列方法处理了,网上都可查这里不多讲
				String jsonString = response.body().string();
				//把访问url得到的数据打印出来
				System.out.print(jsonString);
			}
		});
	}
}

注意:

1、在进行Http请求的时候,最好不要把请求代码放在主线程实现,因为这会是一个耗时的动作,当网络不顺畅时容易引发闪退

2、处理访问url返回的数据,一般是用Json,比如得到以下数据:

[{"id":"1", "version":"1.0", "name":"abc"},

 {"id":"2", "version":"2.0", "name":"def"}]

需要用到代码:

JSONArray jsonArray = new JSONArray(jsonData);
         for (int i=0; i < jsonArray.length(); i++)    {
             JSONObject jsonObject = jsonArray.getJSONObject(i);
             String id = jsonObject.getString("id");
             String name = jsonObject.getString("name");
             String version = jsonObect.getString("version");
             }

//定义一个JSON数组,用于将服务器返回的数据传入到一个JSONArray对象中; 
//然后循环遍历这个JSONArray,
//从中取出每一个元素(JSONObject对象),接下来只需调用getString()方法即可将数据取出。

更多的Json解析知识,网上都有比较详细的教程,这里就不多啰嗦了。还可以顺便学习一下如何使用GSON^_^


关于Post方式:

public static void ReceiveDataFromWeb() {
		OkHttpClient client = new OkHttpClient();

		FormBody formBody = new FormBody.Builder()
				.add("uid", "001")
				.add("key","123")
				.build();

		Request request = new Request.Builder()
				.url("http://www.google.cn")
				.post(formBody)				
				.build();
		Call call = client.newCall(request);
		call.enqueue(new Callback() {
			@Override
			public void onFailure(Call call, IOException e) {
				Log.e("onFailure: ", String.valueOf(e));
			}

			@Override
			public void onResponse(Call call, Response response) throws IOException {
				String jsonString = response.body().string();
				System.out.print(jsonString);

			}
		});
	}

以上就是个人的一点小笔记,希望能帮到进击路上的各位,共勉!

猜你喜欢

转载自blog.csdn.net/Nobody_else_/article/details/88541794