问题描述
- Android网络通信真机测试
-
刚入门学习Android的小白,正在学写Android网络通信,用的是HttpURLConnection,但在真机上测试程序总是崩溃,MainActivity中的代码如下
package com.example.httpurl;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;public class MainActivity extends Activity implements OnClickListener {
public static final int SHOW_RESPONSE=0; private Button sendRequest; private TextView responseText; private Handler handler =new Handler(){ public void handleMessage(Message msg){ switch(msg.what){ case SHOW_RESPONSE: String response =(String) msg.obj; responseText.setText(response); } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); sendRequest =(Button)findViewById(R.id.send_request); responseText=(TextView) findViewById(R.id.response); sendRequest.setOnClickListener(this); } public void onClick(View v){ if(v.getId()==R.id.send_request) { sendRequestWithHttpURLConnection(); }
}
private void sendRequestWithHttpURLConnection() { // TODO Auto-generated method stub new Thread(new Runnable(){ @Override public void run() { // TODO Auto-generated method stub HttpURLConnection connection=null; try{ URL url =new URL("http://www.baidu.com"); connection=(HttpURLConnection)url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(8000); connection.setReadTimeout(8000); InputStream in=connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); StringBuilder response =new StringBuilder(); String line; while((line=reader.readLine()) != null){ response.append(line); } Message message = new Message(); message.what =SHOW_RESPONSE; message.obj =response.toString(); handler.sendMessage(message); }catch(Exception e){ e.printStackTrace(); }finally{ if(connection !=null) { connection.disconnect(); } } } }).start();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}@Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); }
}
后面发现了是xml文件的问题,但是
点击按钮不会返回相应的数据,使用Logcat查看出现以下内容,没太能看懂,求解谢谢!
解决方案
接上电脑,启动程序,看logcat的输出日志
解决方案二:
有加网络权限没?还是看logcat吧
解决方案三:
看下xml布局文件和这个是否对应,在看权限, 能看懂日志就直接看日志