【发布时间】:2014-05-11 12:17:16
【问题描述】:
我试图实现连接到 http 客户端以接收数据的 Android 示例。 http://developer.android.com/training/basics/network-ops/connecting.html
我想实现这样的东西,以便我的 Android 应用可以连接到 php 网络服务以从网页中获取结果。
这里的问题是方法“checkMemberExists(urls[0])”一直给我一个 IOException,因此程序退出并且没有进入 onPostExecute(..)。 我试图实现与上述链接中的示例接近。但不明白为什么它对我不起作用。任何帮助将不胜感激。
private class DbCheckMemberExistsTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
// params comes from the execute() call: params[0] is the url.
try {
String strContentString = checkMemberExists(urls[0]);
return strContentString;
} catch (IOException e) {
return "Unable to retrieve web page. URL may be invalid.";
}
}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(String result) {
memberExists.setText(result);
}
public String checkMemberExists(String email) throws IOException
{
//returns 0 : does not exists
//returns 1 : exists but not activated
//returns 2 : exists and activated
InputStream is = null;
int len = 500;
try
{
URL url = new URL(strDatabaseWebService+"checkmemberexists.php?email="+email);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
int response = conn.getResponseCode();
Log.d("log_debug", "The response is: " + response);
is = conn.getInputStream();
// Convert the InputStream into a string
String contentAsString = readIt(is, len);
Log.d("log_debug", "The response is: " + contentAsString);
//return contentAsString;
return contentAsString;
}
catch (IOException e)
{
return "9";
}
finally
{
if (is != null) {
is.close();
}
}
}
// Reads an InputStream and converts it to a String.
public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
Reader reader = null;
reader = new InputStreamReader(stream, "UTF-8");
char[] buffer = new char[len];
reader.read(buffer);
return new String(buffer);
}
}
【问题讨论】:
-
请访问此。我希望它能帮助你找到你的问题。 stackoverflow.com/questions/18600239/…