我正在尝试从网址获取json数据。我的数据如下所示:
[{"Food1":"Fried Chicken","Food2":"Spagetti","Food3":"Watermelon"}]
我搜索过它,几乎尝试了我能找到的每个代码。但他们不适合我。 当我手动提供json数据时我可以轻松解析它,真正的问题是通过使用HttpClient或Httpurlconnection从url获取数据。我也尝试使用AsyncTask,但是我猜想我做不到。我该怎么办?
Logcat:https://dl.dropboxusercontent.com/u/108584907/logcat.txt
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class yemekhane extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.yemekhane);
TextView tv = (TextView) findViewById(R.id.TextView01);
JSONArray jArray = null;
String result = "";
StringBuilder sb = null;
InputStream is = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
try{
HttpClient httpclient = new DefaultHttpClient();
//Why to use 10.0.2.2
HttpPost httppost = new HttpPost("http://example.com");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection"+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line="0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
String name = "";
try {
jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
name=json_data.getString("Food1");
}
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
tv.setText("test " + name);
}
}`
答案 0 :(得分:0)
感谢您的建议,我终于找到了答案。 首先,我在Android Manifest xml文件中将minsdkversion更改为9。然后我在下面添加了这段代码:
StrictMode.ThreadPolicy policy = new StrictMode.
ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
它对我有用,希望它对其他人也有效:)