我试图从URL解析JSON。这是我的代码,它调用JSONParser类。然后运行它以获取消息" MAIN"我在禁区里烤了它。
MainActivity.java
Button click;
TextView tv;
JSONParser jsonParser;
private static String url="http://webtest.freevar.com/brand.php";
private static final String TAG_SUCCESS="success";
private static final String TAG_RESULT="result";
private static final String TAG_MODELNAME="F_MOB_MODEL_NAME";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
click=(Button)findViewById(R.id.button1);
tv=(TextView)findViewById(R.id.textView1);
click.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Brand_list();
}
});
}
public void Brand_list(){
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("bname","BRAND_HTC"));
try{
JSONObject json = jsonParser.makeHttpRequest(url, "POST", params);
Log.d("Response",json.toString());
try {
int success=json.getInt(TAG_SUCCESS);
if(success==1){
Log.d("success",json.toString());
try{
JSONArray result=json.getJSONArray(TAG_RESULT);
for(int i=0;i<result.length();i++){
JSONObject get=result.getJSONObject(i);
String name=get.getString(TAG_MODELNAME);
tv.append("F_MOB_MODEL_NAME"+name+"\n");
} }
catch(Exception e){
Toast.makeText(getApplicationContext(), "error1", 400).show();
}
}
}
catch (JSONException ej) {
// TODO Auto-generated catch block
ej.printStackTrace();
Toast.makeText(getApplicationContext(), "error", 300).show();
}
}
catch(RuntimeException eq){
Toast.makeText(getApplicationContext(), "main", Toast.LENGTH_LONG).show();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
JSONParser.java
static InputStream isdata = null;
static JSONObject jObj = null;
static String json = "";
public JSONParser()
{
}
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
try {
if(method == "POST")
{
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
isdata = httpEntity.getContent();
}
else if(method == "GET"){
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
isdata = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
isdata, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
isdata.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return jObj;
}
}
检查我收到回复的链接
http://www.webtest.freevar.com/brand.php
这是我的LOG CAT
06-05 13:58:35.106:W / asset(20165):将FileAsset 0x455d0708(zip:/data/app/com.example.brand-2.apk:/resources.arsc)复制到缓冲区大小2276到使它对齐。 06-05 13:58:35.516:I / Adreno-EGL(20165):: EGL 1.4 QUALCOMM build:AU_LINUX_ANDROID_KK_3.5_RB1.04.04.02.006.082_msm8974_refs / tags / AU_LINUX_ANDROID_KK_3.5_RB1.04.04.02.006.082__release_AU() 06-05 13:58:35.516:I / Adreno-EGL(20165):OpenGL ES着色编译器版本:E031.24.00.06 06-05 13:58:35.516:I / Adreno-EGL(20165):建造日期:2014年2月18日星期二 06-05 13:58:35.516:I / Adreno-EGL(20165):当地分公司: 06-05 13:58:35.516:I / Adreno-EGL(20165):远程分支:refs / tags / AU_LINUX_ANDROID_KK_3.5_RB1.04.04.02.006.082 06-05 13:58:35.516:I / Adreno-EGL(20165):本地补丁:无 06-05 13:58:35.516:I / Adreno-EGL(20165):重建分支:没什么 06-05 13:58:39.116:E / AndroidRuntime(20165):致命异常:主要 06-05 13:58:39.116:E / AndroidRuntime(20165):处理:com.example.brand,PID:20165 06-05 13:58:39.116:E / AndroidRuntime(20165):java.lang.NullPointerException:尝试调用虚方法&#39; java.lang.String org.json.JSONObject.toString()&#39;在null对象引用上 06-05 13:58:39.116:E / AndroidRuntime(20165):at com.example.brand.MainActivity.Brand_list(MainActivity.java:88) 06-05 13:58:39.116:E / AndroidRuntime(20165):at com.example.brand.MainActivity $ 1.onClick(MainActivity.java:43) 06-05 13:58:39.116:E / AndroidRuntime(20165):在android.view.View.performClick(View.java:4480) 06-05 13:58:39.116:E / AndroidRuntime(20165):在android.view.View $ PerformClick.run(View.java:18686) 06-05 13:58:39.116:E / AndroidRuntime(20165):在android.os.Handler.handleCallback(Handler.java:733) 06-05 13:58:39.116:E / AndroidRuntime(20165):在android.os.Handler.dispatchMessage(Handler.java:95) 06-05 13:58:39.116:E / AndroidRuntime(20165):在android.os.Looper.loop(Looper.java:157) 06-05 13:58:39.116:E / AndroidRuntime(20165):在android.app.ActivityThread.main(ActivityThread.java:5872) 06-05 13:58:39.116:E / AndroidRuntime(20165):at java.lang.reflect.Method.invoke(Native Method) 06-05 13:58:39.116:E / AndroidRuntime(20165):at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:858) 06-05 13:58:39.116:E / AndroidRuntime(20165):at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:674)
答案 0 :(得分:0)
它的速度更快,你可以使用volley然后制作手动的httprequest ... volley可以为你做所有这些讨厌的事情。
Android volley是一个网络库,用于在不编写大量代码的情况下更轻松,更快速地进行网络调用。默认情况下,所有排球网络调用都是异步工作的,因此我们不必担心再使用asynctask。
Volley有很多功能。其中一些是
您可以在http://www.androidhive.info/2014/05/android-working-with-volley-library-1/
获取有关截击的更多详情和http://www.androidhive.info/2014/09/android-json-parsing-using-volley/
答案 1 :(得分:0)
使用一些库解析json不要自己解析它。使用像gson https://github.com/google/gson之类的东西,这是一个从休息服务中获取json并使用gson http://kylewbanks.com/blog/Tutorial-Android-Parsing-JSON-with-GSON
解析它的示例答案 2 :(得分:0)
Make an HTTP request with android 在这里,检查第一个答案。
对于网络,您可以使用AsyncTask(作为内部类),它将在一个单独的线程中运行它,如下所示:
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new BrandListTask().execute();
}
});
}
public class BrandListTask extends AsyncTask<String,Void,String>{
@Override
protected String doInBackground(String... params) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("bname","BRAND_HTC"));
try{
JSONObject json = jsonParser.makeHttpRequest(url, "POST", params);
Log.d("Response",json.toString());
try {
int success=json.getInt(TAG_SUCCESS);
if(success==1){
Log.d("success",json.toString());
try{
JSONArray result=json.getJSONArray(TAG_RESULT);
for(int i=0;i<result.length();i++){
JSONObject get=result.getJSONObject(i);
String name=get.getString(TAG_MODELNAME);
tv.append("F_MOB_MODEL_NAME"+name+"\n");
}
} catch(Exception e){
// use Log.d("",""); here , you cannot Toast from inside a background thread
//Toast.makeText(getApplicationContext(), "error1", 400).show();
}
}
}catch (JSONException ej) {
// TODO Auto-generated catch block
ej.printStackTrace();
//Toast.makeText(getApplicationContext(), "error", 300).show();
// use Log.d("",""); here , you cannot Toast from inside a background thread
}
}
catch(RuntimeException eq){
//Toast.makeText(getApplicationContext(), "main", Toast.LENGTH_LONG).show();
// use Log.d("",""); here , you cannot Toast from inside a background thread
}
}
return null;
}
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
} //end of inner class
另外,if(method == "POST")
?不!
if(method.equals("POST"))
答案 3 :(得分:0)
我建议您使用Volley Library进行网络调用,然后在API不稳定的情况下使JSON解析为每个请求生成相同类型的JSON数据。如果每次都得到相同的响应,那么你可以使用GSON或Jackson解析器。
但请记住不要在UI线程上调用网络。