android studio用okhttp简单访问配置附demo事例

初次接触安卓开发本次,开发软件android studio,简述一下开发的时候遇到一些问题的解决方案。

首先加入网络访问权限

文件路径 \app\src\main\AndroidManifest.xml

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

图例

android studio用okhttp简单访问配置附demo事例-上流阁

添加okhttp 依赖jar包

File -> Project Structure ->app->Dependencies 点击+号

android studio用okhttp简单访问配置附demo事例-上流阁

android studio用okhttp简单访问配置附demo事例-上流阁

选择Library  Dependency搜索 okhttp 和 okio

android studio用okhttp简单访问配置附demo事例-上流阁

android studio用okhttp简单访问配置附demo事例-上流阁

选择第一个就可以了 然后点击OK 重复上面添加okio添加完后如下

android studio用okhttp简单访问配置附demo事例-上流阁

\app\build.gradle里可以看到加入的jar依赖

android studio用okhttp简单访问配置附demo事例-上流阁

主要核心代码

OkHttpClient mOKHttpClient = new OkHttpClient.Builder()
        .connectTimeout(10, TimeUnit.SECONDS)
        .readTimeout(10, TimeUnit.SECONDS)
        .build();
String url = "";
Request request = new Request.Builder()
        .get()
        .url(url)
        .build();
//new call
Call call = mOKHttpClient.newCall(request);
//请求加入调度
call.enqueue(new Callback() {
    @Override
    public void onFailure(Call call, IOException e) {

    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        String htmlStr = response.body().string();
        try {
            JSONArray jsonArray = new JSONArray(String.valueOf(htmlStr));

            Random rand = new Random();
            int s = rand.nextInt(jsonArray.length());

            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject jsonObject = (JSONObject) jsonArray.get(i);

 }
                }
            }

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
});

参考代码示例代码

package com.jfc.jiangfengcheng.wheretoeat;

import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends Activity {

    private Button button;
    private Button czbutton;
    private JSONObject jsonObject;
    private TextView textView;
    private Map<String, Integer> map = new HashMap<String, Integer>();
    private String str = "";
    private String topstr="";

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    };
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        setContentView(R.layout.activity_main);

        button = (Button) findViewById(R.id.btn);
        czbutton = (Button) findViewById(R.id.cz);
        czbutton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                textView = (TextView) findViewById(R.id.text);
                textView.setText("请点击下面按钮随机去哪吃");
                map.clear();
                textView = (TextView) findViewById(R.id.top);
                textView.setText("等待最终结果...");
            }
        });

        //1.匿名内部类
        button.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Log.i("匿名内部类", "点击事件");
                OkHttpClient mOKHttpClient = new OkHttpClient.Builder()
                        .connectTimeout(10, TimeUnit.SECONDS)
                        .readTimeout(10, TimeUnit.SECONDS)
                        .build();
                String url = "";
                Request request = new Request.Builder()
                        .get()
                        .url(url)
                        .build();
                Log.i("匿名内部类", url);
                //new call
                Call call = mOKHttpClient.newCall(request);
                //请求加入调度
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {

                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        String htmlStr = response.body().string();
                        try {
                            JSONArray jsonArray = new JSONArray(String.valueOf(htmlStr));

                            Random rand = new Random();
                            int s = rand.nextInt(jsonArray.length());

                            for (int i = 0; i < jsonArray.length(); i++) {
                                JSONObject jsonObject = (JSONObject) jsonArray.get(i);

                                Log.i("值", jsonObject.getString("address"));
                                if (i == s) {

                                    if (map.get(jsonObject.getString("address")) != null) {
                                        int a = map.get(jsonObject.getString("address")) + 1;
                                        map.put(jsonObject.getString("address"), a);
                                    } else {
                                        map.put(jsonObject.getString("address"), 1);
                                    }
                                    //这里将map.entrySet()转换成list
                                    List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(map.entrySet());
                                    //然后通过比较器来实现排序
                                    Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
                                        //升序排序
                                        public int compare(Map.Entry<String, Integer> o1,
                                                           Map.Entry<String, Integer> o2) {
                                            return o1.getValue().compareTo(o2.getValue());
                                        }

                                    });
                                    Collections.reverse(list);
                                    int b =0;
                                    topstr ="";
                                    str = "";
                                    for (Map.Entry<String, Integer> key : list) {
                                       if(b==0){
                                           if(key.getValue()>1){
                                               topstr = key.getKey();
                                           }else{
                                               topstr = "暂无结果继续点击";
                                           }
                                       }
                                        str += key.getKey() +":"+key.getValue() + "\n";
                                        b++;
                                    }

                                    handler.post(new Runnable() {
                                        @Override
                                        public void run() {
                                            textView = (TextView) findViewById(R.id.text);
                                            textView.setText(str);
                                            textView = (TextView) findViewById(R.id.top);
                                            textView.setText(topstr);
                                        }
                                    });

                                }
                            }

                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

                        Log.i("参数", htmlStr);
                    }
                });

            }
        });

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }

    @Override
    public void onStart() {
        super.onStart();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client.connect();
        Action viewAction = Action.newAction(
                Action.TYPE_VIEW, // TODO: choose an action type.
                "Main Page", // TODO: Define a title for the content shown.
                // TODO: If you have web page content that matches this app activity's content,
                // make sure this auto-generated web page URL is correct.
                // Otherwise, set the URL to null.
                Uri.parse("http://host/path"),
                // TODO: Make sure this auto-generated app URL is correct.
                Uri.parse("android-app://com.jfc.jiangfengcheng.wheretoeat/http/host/path")
        );
        AppIndex.AppIndexApi.start(client, viewAction);
    }

    @Override
    public void onStop() {
        super.onStop();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        Action viewAction = Action.newAction(
                Action.TYPE_VIEW, // TODO: choose an action type.
                "Main Page", // TODO: Define a title for the content shown.
                // TODO: If you have web page content that matches this app activity's content,
                // make sure this auto-generated web page URL is correct.
                // Otherwise, set the URL to null.
                Uri.parse("http://host/path"),
                // TODO: Make sure this auto-generated app URL is correct.
                Uri.parse("android-app://com.jfc.jiangfengcheng.wheretoeat/http/host/path")
        );
        AppIndex.AppIndexApi.end(client, viewAction);
        client.disconnect();
    }
}

如果有什么疑问欢迎留言提问共同探讨。

*文章为作者独立观点,不代表上流阁立场
本文由 江风成 授权 上流阁 发表,并经上流阁编辑。转载此文章须经作者同意,并请附上出处(上流阁)及本页链接。原文链接https://www.o6c.com/android/2017/08/12/1063.html
发表评论

1 条评论
相关文章
java和安卓中对Map的key值和value值进行升序降序排序干货
java和安卓中对Map的key值和value值进行…
javaweb开发程序员php开发,微信开发。接受定制开发

最新评论