java - 在 Android Studio 中使用 Web Api 检索 Json 数据

标签 java android json

我是 Android 的新手,当我尝试导入时

import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient; 

进入我的 MainActivity.java 文件,我无法执行它。

我更改了我的 gradle 并尝试了另一个 jar 文件,但它不起作用。

这是我的 gradle 文件:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"
    useLibrary 'org.apache.http.legacy'

    defaultConfig {
        applicationId "net.learn2develop.json"
        minSdkVersion 9
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:23.0.1'
    compile 'org.apache.httpcomponents:httpcore:4.3.2'
    compile 'org.apache.httpcomponents:httpclient:4.5'
    compile 'com.google.code.gson:gson:2.3.1'
}

这是 MainActivity.java:

package net.learn2develop.json;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;


import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;




public class MainActivity extends AppCompatActivity {


    public String readJSONFeed(String URL) {
        StringBuilder stringBuilder = new StringBuilder();
        HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet;

        try {
            HttpResponse response = httpClient.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
                InputStream inputStream = entity.getContent();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(inputStream));
                String line;
                while ((line = reader.readLine()) != null) {
                    stringBuilder.append(line);
                }
                inputStream.close();
            } else {
                Log.d("JSON", "Failed to download file");
            }
        } catch (Exception e) {
            Log.d("readJSONFeed", e.getLocalizedMessage());
        }
        return stringBuilder.toString();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

这是 XML 代码:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Latitude" />

    <EditText
        android:id="@+id/txtLat"
        android:layout_width="320dp"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="numberDecimal"
        android:text="37.77493" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Longitude" />

    <EditText
        android:id="@+id/txtLong"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="numberDecimal"
        android:text="-122.419416"  />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Get Weather"
        android:onClick="btnGetWeather" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Postal Code" />

    <EditText
        android:id="@+id/txtPostalCode"
        android:layout_width="320dp"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="number"
        android:text="89118" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Get Places"
        android:onClick="btnGetPlaces" />

</LinearLayout>

最佳答案

sdk 23 不再支持

HttpClient。您必须使用 URLConnection 或降级到 sdk 22 (编译 'com.android.support:appcompat -v7:22.2.0')

如果您需要 sdk 23,请将其添加到您的 gradle 中:

android {
    useLibrary 'org.apache.http.legacy'
}

您也可以尝试下载 HttpClient jar 并将其直接包含到您的项目中

  1. https://stackoverflow.com/a/32649055/5202007
  2. HttpClient won't import in Android Studio

关于java - 在 Android Studio 中使用 Web Api 检索 Json 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32943700/

相关文章:

android - 如何使用 Espresso 测试 Android 应用程序已关闭

android - 带有选项卡的 Viewpager 下方的静态按钮 - Actionbarsherlock

java - 如何使用 svnkit 列出本地修改/未版本控制的文件?

java - 从 cmd 但不是 Eclipse 运行时出现 NoClassDefFound 错误

android - IOError : [Errno 2] No such file or directory: u'/. ......./RetroApp-debug.apk'

python - 在 Python 中将对象保存到 JSON 或 XML 文件中

java - Elasticsearch 中的 JSON 后编码

php - 可以使用 JSON 将数据存储在 mysql 数据库中吗?

java - 将对象映射到多个属性 (Java)

java - 如何将一个简单的 GUI java 类转换为 applet?