这是我用来获取json数据的代码(仍在处理小数据以了解json解析但我在httpClient,httpGet,httpResponseLine中被弃用。我不知道“弃用”是什么意思。所以你能不能帮助我知道弃用的含义,还要看看总是出现空字符串结果的代码?
private String getJsonData() {
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
result=builder.toString();
return result;
}
}
catch(Exception e) {}
return result;
}
其余的代码:调用部分:
String s = getJsonData();
String result,url="https://api.myjson.com/bins/51umq";
谢谢,任何帮助将不胜感激:)
答案 0 :(得分:0)
由于 HttpClient 已弃用,您应该使用 HttpUrlConnection 类从服务器获取json文件。
workaround
答案 1 :(得分:0)
我认为你不应该使用deprecated
个对象(函数)。为什么?因为在将来,您的代码可能不再有效(您的代码需要多长时间才能完成Google)。 AFAIK,您应该使用Volley来处理传输网络数据。它由Google网站推荐:
Volley是一个HTTP库,它使Android应用程序的网络更容易,最重要的是,更快。
简单的请求:
//Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.google.com";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// Display the first 500 characters of the response string.
mTextView.setText("Response is: "+ response.substring(0,500));
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
mTextView.setText("That didn't work!");
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
P / s:别忘了将Volley Library添加到您的项目中
答案 2 :(得分:0)
我在这里使用LoopJ AsyncHttpClient http://loopj.com/android-async-http/ .. 为了获得更优雅的结果,我建议http://square.github.io/retrofit/以便您拥有Java接口。
在“getJsonData()”中,您可以放置此代码。请记住在gradle build中添加库。
AsyncHttpClient client = new AsyncHttpClient();
client.get("https://api.myjson.com/bins/51umq",new JsonHttpResponseHandler(){
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
Log.d("JSONObject", ":" + response);
try{
JSONArray books = response.getJSONArray("book");
int length = books.length();
for(int i=0;i<length;i++){
JSONObject content = books.getJSONObject(i);
Log.d("Author",":" + content.getString("author"));
}
}catch (JSONException e){
e.printStackTrace();
}
}
@Override
public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
Log.d("onFailure", ":" + responseString);
}
});