-1
即时通讯尝试从我的网站读取字符串。该网站返回与PHP呼应会话ID。我只是想读会话ID之前,我的onCreate与后台作业调用JSON解析方法从从URL读取Android字符串
()函数。必须有一个简单的函数来从网站读取一个字符串。希望有人能帮助我。 非常感谢
即时通讯尝试从我的网站读取字符串。该网站返回与PHP呼应会话ID。我只是想读会话ID之前,我的onCreate与后台作业调用JSON解析方法从从URL读取Android字符串
()函数。必须有一个简单的函数来从网站读取一个字符串。希望有人能帮助我。 非常感谢
try {
URL url = new URL("http://www.vogella.com");
HttpURLConnection con = (HttpURLConnection) url
.openConnection();
readStream(con.getInputStream());
} catch (Exception e) {
e.printStackTrace();
}
private void readStream(InputStream in) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
参考http://www.vogella.com/tutorials/AndroidNetworking/article.html
试试这个
public class check extends AsyncTask<String , Void, Integer>{
private ProgressDialog dialog1;
protected void onPreExecute() {
dialog1 = ProgressDialog.show(currentclass.this, "", "Wait.......");
}
protected void onPostExecute(Integer feed) {
dialog1.dismiss();
super.onPostExecute(feed);
}
protected Integer doInBackground(String... params) {
// TODO Auto-generated method stub
System.out.println(" do in abckground");
String URL_request = "http://your url";
String response = MyWebService.methodForAsynckTask(URL_request);
}
}
调用此为
new checkUpdateVersion().execute();
然后
public static String methodForAsynckTask(String URL){
try{
String responseMessage = "";
HttpClient httpclient = new DefaultHttpClient();
HttpParams params = httpclient.getParams();
HttpConnectionParams.setConnectionTimeout(params, REGISTRATION_TIMEOUT);
HttpConnectionParams.setSoTimeout(params, WAIT_TIMEOUT);
ConnManagerParams.setTimeout(params, WAIT_TIMEOUT);
HttpGet httpGet = new HttpGet(URL);
HttpResponse response = httpclient.execute(httpGet);
System.out.println("response forn server :"+response);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseMessage = out.toString();
System.out.println("resonse message :"+responseMessage);
return responseMessage;
}
else{
Log.w("HTTP1:",statusLine.getReasonPhrase());
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
Log.w("HTTP2:",e);
responseMessage = e.getMessage();
} catch (IOException e) {
Log.w("HTTP3:",e);
responseMessage = e.getMessage();
}catch (Exception e) {
Log.w("HTTP4:",e);
responseMessage = e.getMessage();
}
return responseMessage;
}
我应该在哪里打第一个街区?在onCreate()? – user3659544
no no no。你不应该在onCreate上做任何网络活动。阅读关于AsyncTask并在asyc任务中执行网络活动,一旦你得到你需要的更新UI – nizammoidu
好吧,我明白了。我可以调用这个和JSON解析一样的AsyncTask吗? – user3659544