我想通过Web服务器接收和发送数据,但代码不起作用 我该怎么做才能使这个代码工作?
请注意onCreate
中的此代码try {
URL url = new URL("http://myweb.com/");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
InputStream Stream = connection.getInputStream();
InputStreamReader reader = new InputStreamReader(Stream);
BufferedReader b = new BufferedReader(reader);
StringBuilder s = new StringBuilder();
String str ="";
while ((str = b.readLine())!=null) {
s.append(str);
}
String data = s.toString();
TextView myText = (TextView) findViewById(R.id.Text);
myText.setText(data);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
答案 0 :(得分:0)
确保您在Android中的单独线程上执行与网络相关的任务。另外,请检查您是否设置了INTERNET
权限。
如果您想从其他线程更新UI,则必须使用
runOnUiThread (new Runnable () {
public void run() {
//update ui in here
}
}
答案 1 :(得分:0)
所有代码都在主线程中运行,主线程应该始终用于设置UI和侦听UI事件,例如点击侦听器。
此线程不允许网络呼叫,因为它们可能需要很长时间。使用android的AsyncTask API,用于在单独的线程中运行代码。
为所有GET请求任务创建一个类如下所示的类。
public class DownloadTask extends AsyncTask<String, Void, Integer> {
private String TAG = "InDownloadTask";
private DownloadCallback callback;
private String data;
public DownloadTask(DownloadCallback cb){
callback = cb;
}
@Override
protected Integer doInBackground(String... params) {
Integer result = 0;
HttpURLConnection urlConnection;
try {
URL url = new URL(params[0]);
urlConnection = (HttpURLConnection) url.openConnection();
int statusCode = urlConnection.getResponseCode();
if (statusCode == 200) {
BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = r.readLine()) != null) {
response.append(line);
}
data = response.toString();
result = 1;
} else {
result = 0;
}
} catch (Exception e) {
Log.d(TAG, e.getLocalizedMessage());
}
return result;
}
@Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
callback.onFinishDownload(data, integer);
}
}
创建一个我们用于上述类的回调接口。
public interface DownloadCallback {
public void onFinishDownload(String data, Integer result);
}
现在来自你的活动onCreate
String url = "http://myweb.com/";
new DownloadTask(new DownloadCallback() {
public void onFinishDownload(String data, Integer result) {
if(result == 1)
myText.setText(data);
else
myText.setText("Error");
}
}).execute(url);
如果您有许多与网络相关的操作,请使用Volley等网络库来处理此问题。