zoukankan      html  css  js  c++  java
  • Android Studio 学习(五)网络

    HttpURLConnection

    OkHttp

    • 添加依赖
    • 编辑 app/build.gradle 在dependencies闭包中添加
      implementation 'com.squareup.okhttp3:okhttp:3.11.0'

    GET

    • OkHttpClient client = new OkHttpClient();//创建Client对象
    • Request request = new Request.Builder().url("https://www.baidu.com").build();
    • Response response = client.newCall(request).execute();//获取返回数据
    • String respnseData=response.body().string();//将返回的数据变成string、

    POST

    • OkHttpClient client = new OkHttpClient();//创建Client对象
    • RequestBody rb= new FormBody.Builder().add("username","admin").build();
    • Request request = new Request.Builder().url("https://www.baidu.com").post(rb).build();
    • Response response = client.newCall(request).execute();//获取返回数据

    使用okhttp发送请求

    public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    TextView responseText;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = (Button) findViewById(R.id.button);
        responseText = (TextView) findViewById(R.id.textView);
        button.setOnClickListener(this);
    }
    
    @Override
    public void onClick(View view) {
        if(view.getId()==R.id.button)
        {
            sendRequestWithOKHttp();
        }
    }
    private  void  sendRequestWithOKHttp()
    {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder().url("https://www.baidu.com").build();
                    Response response = client.newCall(request).execute();
                    String respnseData=response.body().string();
                    showResponse(respnseData);
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    private void showResponse(final  String response)
    {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                responseText.setText(response);
            }
        });
    }
    

    }

    解析XML

    Pull解析

    private void parseXMLWITHPull (String xmlData)
    {
    try {
    XmlPullParserFactory factory = XmlPullParserFactory.newInstance();//获取实例
    XmlPullParser xmlPullParser = factory.newPullParser();
    xmlPullParser.setInput(new StringReader(xmlData));//将数据设置进去
    int eventType=xmlPullParser.getEventType();//当前解析的事件
    String id="";
    String name="";
    while (eventType!=XmlPullParser.END_DOCUMENT)
    {
    String nodeName = xmlPullParser.getName();
    switch (eventType){
    case XmlPullParser.START_TAG:{
    if("id".equals(nodeName))
    id=xmlPullParser.nextText();
    else if ("name".equals(nodeName))
    name=xmlPullParser.nextText();
    }
    break;
    case XmlPullParser.END_TAG:
    {
    if("app".equals(nodeName))
    {
    Log.d("Main","id is "+id);
    Log.d("Main","name is "+name);
    }
    break;
    }
    }
    eventType=xmlPullParser.next();
    }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    

    解析JSON

    JSONObject

    private void parseJSONWithJSONObject (String jsonData)
    {
    try{
    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 = jsonObject.getString("version");
    Log.d("Main","id"+id);
    Log.d("Main","name"+name);
    Log.d("Main","version"+version);
    }
    }
    catch (Exception e)
    {
    e.printStackTrace();
    }
    }

    GSON

    private void parseJSONWithGSON (String jsonData)
    {
    try{
    Gson gson = new Gson();
    List appList = gson.fromJson(jsonData,new TypeToken<List>(){}.getType());
    for(App app:appList)
    {
    Log.d("Main","id is"+app.getId());
    Log.d("Main","name is"+ app.getName());
    Log.d("Main","version is "+ app.getVersion());
    }
    }
    catch (Exception e)
    {
    e.printStackTrace();
    }
    }

    优化

    public class HttpUtil {
    public static void sendOkHttpRequest(String address,okhttp3.Callback callback)
    {
    OkHttpClient client = new OkHttpClient();
    Request request = new Request.Builder().url(address).build();
    client.newCall(request).enqueue(callback);
    }

    }
    创建这个类
    使用时
    HttpUtil.sendOkHttpRequest("http://545454/get_data.json",new okhttp3.Callback(){
    @Override
    public void onResponse(Call call, Response response) throws IOException {
    String responseData= response.body().string();
    parseJSONWithGSON (responseData);
    }

                @Override
                public void onFailure(Call call, IOException e) {
    
                }
            });
  • 相关阅读:
    SCOI2012 奇怪的游戏
    AHOI2013 差异
    HAOI2018 染色
    HNOI2015 开店
    PKUWC2018 随机游走
    HAOI2015 按位或
    Luogu4859 二项式反演
    CTSC2018 混合果汁
    yii2.0邮件发送问题解决
    yii2.0 elasticsearch模糊查询
  • 原文地址:https://www.cnblogs.com/lancelee98/p/9482411.html
Copyright © 2011-2022 走看看