2013-07-08 171 views
0

我有一個應用程序調用Web服務來獲取PNR狀態。但我是創建網絡服務的新手,所以我已經通過一些視頻和示例來了解如何創建和使用Web服務。創建Web服務時遇到問題

我在stackoverflowhttps://stackoverflow.com/questions/14598485/need-indian-railway-apis-for-making-app-for-pnr-status-train-info-etc和這個問題中提供的所有鏈接,我得到這個:http://pnrapi.alagu.net/

我的代碼是:

XML:activity_status_pnr.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" > 

    <EditText android:id="@+id/et_pnr" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:hint="@string/h" 
     android:maxLength="10" /> 

    <Button android:id="@+id/pnr_status" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="@string/gstatus" 
     android:layout_gravity="center" /> 


</LinearLayout> 

Java代碼:StatusPNR.java

package com.example.infopnr; 

import android.app.Activity; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.EditText; 

import java.io.IOException; 

import android.app.Activity; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.View; 
import android.widget.Button; 
import android.widget.EditText; 

import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.ResponseHandler; 
import org.apache.http.impl.client.BasicResponseHandler; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.impl.client.DefaultHttpClient; 

public class StatusPNR extends Activity { 

    String URL = "http://pnrapi.alagu.net/api/v1.0/pnr/UR_PNR_CODE"; 
    String result = ""; 
    //String deviceId = "xxxxx" ; 
    //final String tag = "Your Logcat tag: "; 

    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_status_pnr); 

     final EditText txtSearch = (EditText)findViewById(R.id.et_pnr); 
     txtSearch.setOnClickListener(new EditText.OnClickListener() 
     { 
      public void onClick(View v){txtSearch.setText("");} 
     }); 

     final Button btnSearch = (Button)findViewById(R.id.pnr_status); 
     btnSearch.setOnClickListener(new Button.OnClickListener(){ 
      public void onClick(View v) { 
       String query = txtSearch.getText().toString(); 
       PNRWebService(query); 

      } 
     }); 

     } 

    private void PNRWebService(String q){ 


    } 
} 

我還沒有創建的Web服務方法尚未作爲我在這裏遇到了一些問題。在某些網站上,我讀到應該使用Apache Web服務器來獲取HTTP客戶端。但是,我不確定,不知道爲什麼會這樣?

我的問題是:

1)是他們的任何需要安裝以獲得web服務器或我們的編碼是足以調用Web服務沒有任何東西任何事先安裝?

2)在PNRWebService()方法中,我需要做什麼才能獲得連接並使用URL調用服務?我知道我需要通過HTTPClient建立連接,但經過許多例子和視頻之後,我並沒有明白他們究竟是怎麼做的?

3)http://pnrapi.alagu.net/與本網站的參考我想獲得PNR狀態?爲了調用這個我需要做的事情,因爲我不知道這個URL是什麼,以及在獲取URL之後還應該做些什麼?

4)我從Apache導入了一些軟件包,我不知道它是否值得?

如果任何人有良好的知識,請幫助他人,然後請讓我知道如何執行。

回答

1

好的。首先,我建議你使用AsyncTask。你可以谷歌它,並找出它是如何完成的。

下面是一個示例代碼

//Main Class 
public class MainActivity extends Activity { 

String url = "http://pnrapi.alagu.net/api/v1.0/pnr/UR_PNR_CODE"; 



//Your call to asynctask 
new asyncTask(this).execute(url); 

} 

//asyncTask class 
import java.io.IOException; 
import java.io.UnsupportedEncodingException; 
import java.net.URLEncoder; 

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 android.app.AlertDialog; 
import android.app.ProgressDialog; 
import android.content.Context; 
import android.content.DialogInterface; 
import android.os.AsyncTask; 
import android.util.Log; 
import android.widget.Toast; 

public class asyncTask extends AsyncTask<String, Void, String> { 
HttpResponse response = null; 
    HttpClient httpClient = new DefaultHttpClient(); 
    private Context context; 
    private ProgressDialog dialog; 
    int code; 
String codeValue = ""; 

    public asyncTask(Context cxt) { 
     context = cxt; 

     dialog = new ProgressDialog(context); 
    } 

    @Override 
    protected String doInBackground(String... arg0) { 

     Log.d("in ASyn Task", arg0[0]); 

     HttpGet httpget = new HttpGet(arg0[0]);//This get your URL 
     Log.d("after url in httpget", "after url"); 


     try { 
      response = httpClient.execute(httpget); 
      StatusLine line = response.getStatusLine(); 
      code = line.getStatusCode(); 
      codeValue = String.valueOf(code); 
      Log.d("code", codeValue); 
      Log.d("Response", "Connected"); 
     } catch (ClientProtocolException e) { 
      // TODO Auto-generated catch block 
      Log.d("Response 2", "not Connected in exception"); 
      e.printStackTrace(); 
     } catch (IOException e) { // TODO Auto-generatedcatch block 
      Log.d("Response 3", e.toString()); 
     } 



     return "Connected !!"; 
    } 

    @Override 
    protected void onPreExecute() { 
     // TODO Auto-generated method stub 
     super.onPreExecute(); 

     dialog.setTitle("Please Wait..."); 
     dialog.show(); 

     // Toast.makeText(asyncTask.this,"Please wait.. !! Uploading data to server",Toast.LENGTH_LONG).show(); 

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

    AlertDialog.Builder alert = new AlertDialog.Builder(context); 
    alert.setTitle("Alert"); 
    if (code == 200) { 
     alert.setMessage("Connection to host established !! ") 
       .setCancelable(false) 
       .setPositiveButton("Ok", 
         new DialogInterface.OnClickListener() { 
          public void onClick(DialogInterface dialog, 
            int id) { 
           dialog.cancel(); 
          } 

         }); 

    } 

    else { 
     alert.setMessage("Error Connecting to server. Try Again") 
       .setCancelable(false) 
       .setPositiveButton("Ok", 
         new DialogInterface.OnClickListener() { 
          public void onClick(DialogInterface dialog, 
            int id) { 
           dialog.cancel(); 
          } 

         }); 
    } 

    AlertDialog alertDialog = alert.create(); 
    alertDialog.show(); 
} 

} 

檢查你的代碼是200 ..如果是你能夠建立與Web服務的連接。(在onPostExecute做在上面的代碼)

希望這有助於

+0

謝謝帕爾!我已經實現了它,但我想問一下,我想調用ansynTask單擊按鈕,當我創建它像這樣:final Button btnSearch =(Button)findViewById(R.id.pnr_status); btnSearch.setOnClickListener(新Button.OnClickListener(){ 公共無效的onClick(視圖v){ \t \t新的AsyncTask(本).execute(URL); } }); – Saggy

+0

它顯示錯誤:構造函數StatusPNR.asyncTask(新View.OnClickListener(){})未定義....在這裏我不能調用on-clickListener事件的構造函數作爲上下文值在那裏。對? – Saggy

+0

我想不可以在OnClick Event上調用asyncTask,如果沒有,那麼程序將如何知道從他們需要獲取PNR的位置以及點擊他們需要啓動過程的位置?我有點混亂。 – Saggy

0

第一件事情,你需要知道的是你要訪問的Web服務是寧靜 web服務。

第二件事,webservice的響應是json格式。(ü可以在這裏使用GSON庫來解析數據)

第三,你需要運行一個後臺進程或使用的AsyncTask對背景thread.You不能在UI線程上執行網絡IO進行網絡交易在Honeycombe或更高版本

幾個教程可以..它只是谷歌..

檢查此鏈接: Android, Web Services, AsyncTask please help a noob/make sure im starting right

如果你仍然有疑問張貼..