2017-02-11 142 views
0

構建一個Android應用程序,將來自RESTful API的Web服務合併到C#中。我希望能夠在此階段檢索出一些原始的JSON,以確保連接正常工作。對於API的本地主機的URL顯示如下數據:Android應用程序返回空值API

The JSON at the local host address

在Android應用程序的URL字符串設置爲外部IP地址,但應用程序只是顯示爲空時,我就要求數據應用程序。

Android應用程序代碼 - 主要活動:

public class MainActivity extends AppCompatActivity{ 

private static final String JSON_URL = 
     "http://**.***.***.***:5495/api/StudentAPI/GetAllStudent"; 

private boolean networkOk; 
TextView output; 

private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() { 
    @Override 
    public void onReceive(Context context, Intent intent) { 
     String message = 
       intent.getStringExtra(myService.MY_SERVICE_PAYLOAD); 
     output.append(message + "\n"); 
    } 
}; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    output = (TextView) findViewById(R.id.output); 

    LocalBroadcastManager.getInstance(getApplicationContext()) 
      .registerReceiver(mBroadcastReceiver, 
        new IntentFilter(myService.MY_SERVICE_MESSAGE)); 

    networkOk = NetworkHelper.hasNetworkAccess(this); 
    output.append("Network ok: " + networkOk); 
} 

@Override 
protected void onDestroy() { 
    super.onDestroy(); 

    LocalBroadcastManager.getInstance(getApplicationContext()) 
      .unregisterReceiver(mBroadcastReceiver); 
} 

public void runClickHandler(View view){ 
    Intent intent = new Intent(this, myService.class); 
    intent.setData(Uri.parse(JSON_URL)); 
    startService(intent); 
} 

public void clearClickHandler(View view){output.setText(""); } 


} 

我的服務:

public class myService extends IntentService { 

public static final String TAG = "MyService"; 
public static final String MY_SERVICE_MESSAGE = "myServiceMessage"; 
public static final String MY_SERVICE_PAYLOAD = "myServicePayload"; 

public myService() { 
    super("MyService"); 
} 

@Override 
protected void onHandleIntent(Intent intent) { 
    Uri uri = intent.getData(); 
    Log.i(TAG, "onHandleIntent: " + uri.toString()); 

    String response; 

    try { 
     response = 
       HttpHelper.downloadUrl(uri.toString()); 
    } catch (IOException e) { 
     e.printStackTrace(); 
     return; 
    } 

    Intent messageIntent = new Intent(MY_SERVICE_MESSAGE); 
    messageIntent.putExtra(MY_SERVICE_PAYLOAD, response); 
    LocalBroadcastManager manager = 
      LocalBroadcastManager.getInstance(getApplicationContext()); 
    manager.sendBroadcast(messageIntent); 

} 

@Override 
public void onCreate() { 
    super.onCreate(); 
    Log.i(TAG, "onCreate"); 
} 

@Override 
public void onDestroy() { 
    super.onDestroy(); 
    Log.i(TAG, "onDestroy"); 
} 
} 

網絡助手:

public class NetworkHelper { 

public static boolean hasNetworkAccess(Context context){ 

    ConnectivityManager cm = (ConnectivityManager) 
      context.getSystemService(Context.CONNECTIVITY_SERVICE); 
    try { 
     NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); 
     return activeNetwork != null && 
       activeNetwork.isConnectedOrConnecting(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
     return false; 
    } 
} 
} 

的Http助手類:

public class HttpHelper { 

/** 
* Returns text from a URL on a web server 
* 
* @param address 
* @return 
* @throws IOException 
*/ 
public static String downloadUrl(String address) throws IOException { 

    InputStream is = null; 
    try { 

     URL url = new URL(address); 
     HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
     conn.setReadTimeout(10000); 
     conn.setConnectTimeout(15000); 
     conn.setRequestMethod("GET"); 
     conn.setDoInput(true); 
     conn.connect(); 

     int responseCode = conn.getResponseCode(); 
     if (responseCode != 200) { 
      throw new IOException("Got response code " + responseCode); 
     } 
     is = conn.getInputStream(); 
     return readStream(is); 

    } catch (IOException e) { 
     e.printStackTrace(); 
    } finally { 
     if (is != null) { 
      is.close(); 
     } 
    } 
    return null; 
} 

/** 
* Reads an InputStream and converts it to a String. 
* 
* @param stream 
* @return 
* @throws IOException 
*/ 
private static String readStream(InputStream stream) throws IOException { 

    byte[] buffer = new byte[1024]; 
    ByteArrayOutputStream byteArray = new ByteArrayOutputStream(); 
    BufferedOutputStream out = null; 
    try { 
     int length = 0; 
     out = new BufferedOutputStream(byteArray); 
     while ((length = stream.read(buffer)) > 0) { 
      out.write(buffer, 0, length); 
     } 
     out.flush(); 
     return byteArray.toString(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
     return null; 
    } finally { 
     if (out != null) { 
      out.close(); 
     } 
    } 
} 

} 
+0

它在localhost上工作嗎? – samirk433

+0

不。因爲我在物理設備上測試,我認爲您需要外部IP地址。 –

+0

設置一個斷點並找出錯誤。你得到200嗎?還有別的嗎?拋出異常?您需要先進行背景研究,沒有人會爲您構建這麼多代碼來進行調試。 –

回答

0

首先,找出問題出在服務中還是應用中。

使用所有給定的參數從here發出HTTP請求,如果它有效,那麼您的服務是OK的。

現在,按照以下步驟找出本地問題。

downloadUrl()上運行調試,並檢查responseCode的值是否爲200,那麼請求是好的,現在只需清理並重建項目。

如果它不是200,然後按照下列:

  1. extends的HttpHelper類從AsyncTask
  2. 現在你的代碼downloadUrl()
  3. 移動到doInBackground()現在,調試這個類responseCode。
+0

我已經採取了上述步驟,發現以下內容: 服務很好,並返回原始json 我有確保端口正在接受防火牆設置內的連接 我按照您的說法重新格式化了代碼,並且在使用公共IP地址(31.185.xx)時連接被拒絕。當使用專用地址(192.168.x.x)時,它會以400 responseCode響應。 –

+0

使用私有IP地址爲此,但在此之前,允許從您的服務器/ dbms等外部請求。在MySQL的情況下,我不得不允許它在Apache。 – samirk433