【问题标题】:Android read json from restful serviceAndroid从restful服务读取json
【发布时间】:2013-07-28 19:06:14
【问题描述】:

我正在尝试从服务获取响应(响应来自 json)。 我检查了设备是否已连接,现在我需要向服务发出 http 请求。我在其他问题上发现了我必须使用后台线程,但我不确定我是否有工作示例。

所以我需要找出如何连接到给定的 uri 并读取响应。 我的服务需要获取内容标头 application/json 才能返回 json,因此在请求之前我还需要设置此标头。

提前谢谢你

更新

package com.example.restfulapp;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.provider.Settings;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;

import java.io.InputStreamReader;
import java.util.concurrent.ExecutionException;


public class MainActivity extends Activity {

    private int code = 0;
    private String value = "";
    private ProgressDialog mDialog;
    private Context mContext;
    private String mUrl ="http://192.168.1.13/myservice/upfields/";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (!isOnline())
        {
            displayNetworkOption ("MyApp", "Application needs network connectivity. Connect now?");
        }

        try {
            JSONObject s = getJSON(mUrl);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

    }

    public class Get extends AsyncTask<Void, Void, String> {
        @Override
        protected String doInBackground(Void... arg) {
            String linha = "";
            String retorno = "";

            mDialog = ProgressDialog.show(mContext, "Please wait", "Loading...", true);

            HttpClient client = new DefaultHttpClient();
            HttpGet get = new HttpGet(mUrl);

            try {
                HttpResponse response = client.execute(get);

                StatusLine statusLine = response.getStatusLine();
                int statusCode = statusLine.getStatusCode();

                if (statusCode == 200) { // Ok
                    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

                    while ((linha = rd.readLine()) != null) {
                        retorno += linha;
                    }
                }
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return retorno;
        }

        @Override
        protected void onPostExecute(String result) {
            mDialog.dismiss();
        }
    }

    public JSONObject getJSON(String url) throws InterruptedException, ExecutionException {
        setUrl(url);

        Get g = new Get();

        return createJSONObj(g.get());
    }

    private void displayNetworkOption(String title, String message){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder
                .setTitle(title)
                .setMessage(message)
                .setPositiveButton("Wifi", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
                    }
                })
                .setNeutralButton("Data", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        startActivity(new Intent(Settings.ACTION_DATA_ROAMING_SETTINGS));
                    }
                })
                .setNegativeButton("No", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        return;
                    }
                })
                .show();
    }

    private boolean isOnline() {
        ConnectivityManager cm =
                (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo netInfo = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnectedOrConnecting()) {
            return true;
        }
        return false;
    }


}

这会引发错误: Gradle:找不到符号方法 setUrl(java.lang.String) Gradle:找不到符号方法 createJSONObj(java.lang.String)

【问题讨论】:

  • 我尝试了一些来自网络的示例,但都不起作用,其中大多数都需要使用 permitAll,这不是正确的方法
  • 你能给我们看看代码和相关的文章或帖子吗?看起来您正在等待某人编写您的代码。显示您的代码,我相信有人会帮助修复它。
  • 请提供代码示例以及您遇到的问题。
  • 在开始深入研究如何自己实现这一切之前,请花 5 分钟时间看一下:kpbird.com/2013/05/volley-easy-fast-networking-for-android.html 这就是要走的路。或者,如果您懒惰阅读,请观看youtube.com/watch?v=yhv8l9F44qo

标签: java android json http


【解决方案1】:

在 EvZ 认为他生来无所不知的贬损回应之后,我最终得到了一个 MyTask 子类,我在我的 Activity 的 onCreate 中这样调用它。

new MyTask().execute(wserviceURL);



private class MyTask extends AsyncTask<String, Void, String> {
            @Override
            protected String doInBackground(String... urls) {
                URL myurl = null;
                try {
                    myurl = new URL(urls[0]);
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
                URLConnection connection = null;
                try {
                    connection = myurl.openConnection();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                connection.setConnectTimeout(R.string.TIMEOUT_CONNECTION);
                connection.setReadTimeout(R.string.TIMEOUT_CONNECTION);

                HttpURLConnection httpConnection = (HttpURLConnection) connection;
                httpConnection.setRequestProperty("Content-Type", getString(R.string.JSON_CONTENT_TYPE));

                int responseCode = -1;
                try {
                    responseCode = httpConnection.getResponseCode();
                } catch (SocketTimeoutException ste) {
                    ste.printStackTrace();
                }
                catch (Exception e1) {
                    e1.printStackTrace();
                }
                if (responseCode == HttpURLConnection.HTTP_OK) {
                    StringBuilder answer = new StringBuilder(100000);

                    BufferedReader in = null;
                    try {
                        in = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    String inputLine;

                    try {
                        while ((inputLine = in.readLine()) != null) {
                            answer.append(inputLine);
                            answer.append("\n");
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    httpConnection.disconnect();
                    return answer.toString();
                }
                else
                {
                    //connection is not OK
                    httpConnection.disconnect();
                    return null;
                }

            }

            @Override
            protected void onPostExecute(String result) {
                String userid = null;
                String username = null;
                String nickname = null;
                if (result!=null)
                {
                    try {
                        //do read the JSON here
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
                //stop loader dialog
                mDialog.dismiss();


            }

        }

lory105 的回答引导我找到答案附近的某个地方,thanx。

【讨论】:

    【解决方案2】:

    这里是一个如何处理 HTTP 响应并转换为 JSONObject 的示例:

    /**
     * convert the HttpResponse into a JSONArray
     * @return JSONObject
     * @param response
     * @throws IOException 
     * @throws IllegalStateException 
     * @throws UnsupportedEncodingException 
     * @throws Throwable
     */
    public static JSONObject processHttpResponse(HttpResponse response) throws UnsupportedEncodingException, IllegalStateException, IOException  {
        JSONObject top = null;
        StringBuilder builder = new StringBuilder();
        try {
                BufferedReader reader = new BufferedReader(
                                            new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
    
                for (String line = null; (line = reader.readLine()) != null;) {
                    builder.append(line).append("\n");
                    }
    
            String decoded = new String(builder.toString().getBytes(), "UTF-8");
            Log.d(TAG, "decoded http response: " + decoded);
    
            JSONTokener tokener = new       JSONTokener(Uri.decode(builder.toString()));
    
            top = new JSONObject(tokener);
    
    
    
      } catch (JSONException t) {
            Log.w(TAG, "<processHttpResponse> caught: " + t + ", handling as string...");
    
        } catch (IOException e) {
            Log.e(TAG, "caught: " + e, e);
        } catch (Throwable t) {
            Log.e(TAG, "caught: " + t, t);
        }
         return top;
    }
    

    【讨论】:

      【解决方案3】:

      从 Android 3+ 开始,http 连接必须在单独的线程中完成。 Android 提供了一个名为 AsyncTask 的类来帮助您完成这项工作。

      Here 你可以找到一个很好的 AsyncTask 示例,它执行 http 请求并接收 JSON 响应。

      请记住,在 doInBackgroud(..) 方法中,您不能修改 UI,例如启动 Toast、更改活动或其他。您必须使用 onPreExecute() 或 onPostExecute() 方法来执行此操作。

      添加

      对于mDialog和mContext变量,添加下面的代码,创建JSONTask的时候写new JSONTask(YOUR_ACTIVITY)

      public abstract class JSONTask extends AsyncTask<String, Void, String> {
      
        private Context context = null;
        ProgressDialog mDialog = new ProgressDialog();
      
        public JSONTask(Context _context){ context=_context; }
      

      ..

      【讨论】:

      • 好的,我之前找到了这个例子,但是 mDialog, mContext 但是我得到像 Gradle 之类的错误:找不到符号变量 mDialog 这些 mXXXX 变量是如何声明的?我一定在这里遗漏了一些非常简单的东西。
      • 查看我在答案中的添加
      • 我在我的活动课上声明了它们。现在我收到错误 Gradle: 找不到符号方法 setUrl(java.lang.String) Gradle: 找不到符号方法 createJSONObj(java.lang.String) 我将用我当前的代码更新我的帖子
      • 首先使用 IDE(如 ECLIPSE)进行编程,并且在编写代码期间检测到所有这些错误。其次,这些错误的发生是因为您必须个性化您的代码并创建您喜欢的个人方法,如 setURL() 或 createJSONOb()。
      • 我用的是安卓工作室。无论如何,谢谢
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多