Android通过Get方法获取Json数据

manifest文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.wo.checkdrugdemo">

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:weightSum="1">
    <TableLayout
        android:layout_width="match_parent"
        android:layout_height="56dp">
        <TableRow>
            <TextView
                android:layout_weight="1"
                android:text="国字准号:"
                android:layout_height="50dp"
                android:textSize="24dp"/>

            <EditText
                android:id="@+id/inputNum"
                android:text="Z20093192"
                android:layout_width="240dp"
                android:layout_height="50dp"
                />
        </TableRow>
    </TableLayout>

    <TableLayout
        android:layout_width="match_parent"
        android:layout_height="56dp">
        <TableRow>
            <TextView android:layout_weight="1"/>
            <Button
                android:id="@+id/btnCheck"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="查询"
                android:textSize="30dp" />

            <TextView android:layout_weight="1"/>

            <Button
                android:id="@+id/btnExit"
                android:layout_weight="1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="退出"
                android:textSize="30dp"/>
            <TextView android:layout_weight="1"/>
        </TableRow>
    </TableLayout>
    <TextView
        android:id="@+id/display"
        android:textSize="24dp"
        android:scrollbars="vertical"
        android:scrollbarStyle="outsideOverlay"
        android:scrollbarFadeDuration="2000"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

这里写图片描述

Activity文件代码

package com.example.wo.checkdrugdemo;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by yuanlifu on 2016/9/21.
 */
public class MainActivity extends AppCompatActivity {
    private Button btnExit;
    private Button btnCheck;
    private EditText inputText = null;
    private TextView display;
    static String url = "http://www.tngou.net/api/drug/number?number=";
    @SuppressLint("NewApi")
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_layout);

        btnExit = (Button) findViewById(R.id.btnExit);
        btnCheck = (Button) findViewById(R.id.btnCheck);
        inputText = (EditText) findViewById(R.id.inputNum);
        display = (TextView) findViewById(R.id.display);
        display.setMovementMethod(new ScrollingMovementMethod());//让TextView也能滚动的方法
                                                                 //还要配合XML文件中的TextView属性设置
        btnCheck.setOnClickListener(new View.OnClickListener(){//查询键处理
            @Override
            public void onClick(View v) {
                if (inputText.getText().toString()!=null){
                    try{
                        processResponse(
                                searchRequest(inputText.getText().toString())
                        );
                    }catch (Exception e){
                        Log.v("Exception Google search","Exception:"+e.getMessage());
                    }
                }
              //  inputText.setText("");//清空
            }
        });
        btnExit.setOnClickListener(new View.OnClickListener(){//取消键处理
            @Override
            public void onClick(View v) {
                inputText.setText("");//清空输入框
            }
        });
        closeStrictMode();
    }

    /**
     * 据说是如果用android端 使用HttpURLConnection请求,得到的getResponseCode()会返回-1
     * 主要问题在于线程, 要单独走一个线程, 不能直接走主线程
     * 解决方法有两种:
     *一:为该请求单独起一个线程
     *二:自己写个方法:
     */
    public static void closeStrictMode() {//不知道干嘛的,但是加上去之后就可以读取到网站的内容了
        StrictMode.setThreadPolicy(
        new StrictMode
                .ThreadPolicy
                .Builder()
                .detectAll()
                .penaltyLog()
                .build());
    }
    public String searchRequest(String searchString) throws IOException {//用于获取网站的Json数据

        String newFeed = url+searchString;
        StringBuilder response = new StringBuilder();

        Log.v("gsearch","gsearch url:"+newFeed);
        URL url = new URL(newFeed);
        HttpURLConnection httpconn = (HttpURLConnection) url.openConnection();
        httpconn.setReadTimeout(10000);
        httpconn.setConnectTimeout(15000);
        httpconn.setRequestMethod("GET");
        httpconn.setDoInput(true);

        httpconn.connect();
        if (httpconn.getResponseCode()==200){//HttpURLConnection.HTTP_OK
            BufferedReader input = new BufferedReader(new InputStreamReader(httpconn.getInputStream()),8192);
            String strLine = null;
            while ((strLine = input.readLine()) != null){
                response.append(strLine);
            }
            input.close();
        }
        return response.toString();
    }

    public void processResponse(String resp){//用于解析Json数据
        JSONObject root = null;
        try {
            root = new JSONObject(resp);
//            display.setText("description:"+root.getString("description"));//纯Json数据的显示
//            display.setText("message:"+root.getString("message"));
            //另外Json数组的运用也是常用的
            String htmlText = new String();//用于存放从Json数据里剥离的HTML数据
            htmlText = root.getString("message");//从Json数据里将HTML数据剥离出来
            display.setText(Html.fromHtml(htmlText));//Json数据里面的HTML数据解析
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页