構建一個Android應用程序,將來自RESTful API的Web服務合併到C#中。我希望能夠在此階段檢索出一些原始的JSON,以確保連接正常工作。對於API的本地主機的URL顯示如下數據:Android應用程序返回空值API
在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();
}
}
}
}
它在localhost上工作嗎? – samirk433
不。因爲我在物理設備上測試,我認爲您需要外部IP地址。 –
設置一個斷點並找出錯誤。你得到200嗎?還有別的嗎?拋出異常?您需要先進行背景研究,沒有人會爲您構建這麼多代碼來進行調試。 –