我正在尝试构建一个Android应用程序,我想在其中显示从网址获取的数据。我用JSON试了一下。它没有显示任何错误,但我无法得到结果。这就是我尝试的方式: -
//MainActivity.java
package com.example.login1;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.widget.TextView;
public class MainActivity extends Activity {
//URL to get JSON Array
private static String url = "http://demo.vtiger.com/webservice.php?operation=getchallenge&username=admin";
//JSON Node Names
private static final String TAG_RESULT = "result";
private static final String TAG_TOKEN = "token";
JSONArray token = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
// Creating new JSON Parser
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting JSON Array
token = json.getJSONArray(TAG_RESULT);
JSONObject c = token.getJSONObject(0);
// Storing JSON item in a Variable
String token = c.getString(TAG_TOKEN);
//Importing TextView
final TextView gettoken = (TextView)findViewById(R.id.lblToken);
//Set JSON Data in TextView
gettoken.setText(token);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
这是我的JSONParser类: -
package com.example.login1;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
我是android和JSON的新手,请帮助我。谢谢。 的
//AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.login1"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="9"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.login1.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
答案 0 :(得分:0)
您的错误肯定是“android.os.NetworkOnMainThreadException”,因为您无法在UIThread中发出HTTP请求。使用AsyncTask。
改变这个:
TextView gettoken;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
this.gettoken = (TextView)findViewById(R.id.lblToken);
new AsyncTask<Void, Void, Void>() {
String token;
@Override
protected Void doInBackground(Void... params) {
// Creating new JSON Parser
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting JSON Array
token = json.getJSONArray(TAG_RESULT);
JSONObject c = token.getJSONObject(0);
// Storing JSON item in a Variable
token = c.getString(TAG_TOKEN);
//Importing TextView
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
//Set JSON Data in TextView
gettoken.setText(token);
}
}.execute();
}
答案 1 :(得分:0)
您的HttpPost
应该是HttpGet
。你想拉数据而不是推它。
答案 2 :(得分:0)
我试过这个方法:
public String jsonTEST(String URL) {
//new JSON parser instance
JsonParser jParser = new JsonParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(URL);
try {
JSONObject test = json.getJSONObject("result");
return test.get string("token");
} catch (JSONException e) {
e.printStackTrace();
}
}
使用您提供的URL,我在此异步任务中调用它:
private class JsonGetTest extends AsyncTask<String, Void, Object> {
@Override
protected Object doInBackground(String... params) {
try {
String token = jsonTEST("https://demo.vtiger.com/webservice.php?operation=getchallenge&username=admin");
} catch (Exception e) {
return e;
}
}
我打电话给:
new JsonGetTest().execute();
当我调试并查看JSONObject测试时,我看到了这个:
{"expireTime":1404744505,"token":"53bab20ddf1b5","serverTime":1404744205}
这是正确的。