我在链接中的Web服务器中有一些数据:http://tonyjoseph.site90.com/demo/现在我需要使用url连接将这些数据接收到我的android中。我在异步任务中给出了一些代码。代码如下:
String link18="http://tonyjoseph.site90.com/demo/";
URL url18 = new URL(link18);
URLConnection conn18 = url18.openConnection();
conn18.setDoOutput(true);
OutputStreamWriter wr18 = new OutputStreamWriter (conn18.getOutputStream());
BufferedReader reader18 = new BufferedReader (new InputStreamReader(conn18.getInputStream()));
StringBuilder sb18=new StringBuilder();
String line18 = null;
while((line18 = reader18.readLine()) !=null)
{
sb18.append(line18);
break;
}
status18=sb18.toString();
Log.d("Status 18",status18);// Nothing displayed in logcat even the Status18 tag is not displayed in log
System.out.println(status18); // Here also System.out.println tag is not displayed in logcat.
但问题是我在String status18中获得空值。在异步任务的doinBackground中调用此代码之后。当我试图向这个值吐司时,它显示出一个空的吐司。
如果我错了,有人可以通过纠正代码来帮助我。提前谢谢..
答案 0 :(得分:0)
您没有提到您使用哪种语言连接android和服务器
假设您使用Jason,请遵循以下代码:
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://yourwebsiteAdrress");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", "connection success ");
}
catch(Exception e){
Log.e("Fail 1", e.toString());
showToast("Connect to the internet");}
try
{
BufferedReader reader = new BufferedReader
(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
}
catch(Exception e)
{Log.e("Fail 2", e.toString());}
try
{
//to receive web page information
JSONObject json_data = new JSONObject(result);
Yourjsonmessage=(json_data.getInt("code"));
// in my case the information is error message so I wanted to print it to the user
if(!"".equals( Yourjsonmessage))
{
showToast( Yourjsonmessage);
}
else if
{
showToast("done!");
}