2013-07-28 26 views
0

我試圖從服務中得到響應(響應出現在json中)。 我做了我的檢查,如果設備連接,現在我需要對服務進行http請求。我發現在其他問題上我必須使用後臺線程,但我不確定是否有工作示例。Android從平靜的服務中讀取json

因此,我需要找出如何可以連接到給定的uri並閱讀響應。 我的服務需要得到一個內容頭application/json來返回一個json,所以在請求之前我需要設置這個頭。

預先感謝您

UPDATE

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; 
    } 


} 

這引發錯誤: 搖籃:找不到符號法setUrl(java.lang.String中) 搖籃:找不到符號法createJSONObj(java中。 lang.String)

+0

我嘗試了很多來自web的例子,沒有起作用,大部分都需要使用permitAll而不是正確的方式 –

+0

你能告訴我們代碼和相關文章或文章嗎?看起來你正在等待某人編寫你的代碼。顯示你的代碼,我相信有人會幫助解決它。 – EvZ

+0

請提供一個代碼示例以及您卡在哪裏。 –

回答

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。

0

從Android 3+開始,http連接必須在單獨的線程內完成。 Android提供了一個名爲AsyncTask的類,可以幫助您做到這一點。

Here你可以找到一個AsyncTask的例子,它執行一個http請求並接收一個JSON響應。

請記住,在doInBackgroud(..)方法中,您不能修改UI,例如啓動Toast,更改活動或其他。您必須使用onPreExecute()或onPostExecute()方法來執行此操作。

ADD

對於支持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; } 

..

+0

好吧,我發現這個例子較早,但mDialog,mContext,但我得到像Gradle錯誤:無法找到符號變量mDialog 這些mXXXX變量如何得到聲明?我必須在這裏錯過一些非常簡單的事情。 –

+0

看到我在answare中添加 – lory105

+0

我在我的活動課上宣佈了他們。 現在我得到錯誤 Gradle:找不到符號方法setUrl(java.lang.String) Gradle:找不到符號方法createJSONObj(java.lang.String) 我要用我當前的代碼更新我的帖子 –

0

這裏是如何的例子處理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; 
}