sureballse 华中科技大学 学生  2016年01月20日
HttpURLConnection运行错误
今天按照第一行代码——android这本书编写第10章HttpURLConnection,与书上的程序是一模一样的,可是就是会出现问题。


代码如下

import android.app.Activity;


import android.os.Message;

import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class FirstActivity extends Activity implements View.OnClickListener {
public static final int SHOW_RESPONSE=0;
private Button sendRequest;
private TextView responseText=null;

private Handler handler=new Handler() {
/* @Override*/

public void handleMessage(Message msg){
/*super.handleMessage(msg);*/
switch(msg.what){
case SHOW_RESPONSE:
String response=(String)msg.obj;
responseText.setText(response);
/* break;*/
}

}
};


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
requestWindowFeature(Window.FEATURE_NO_TITLE);
sendRequest=(Button)findViewById(R.id.send_request);
responseText = (TextView) findViewById(R.id.response_text);
sendRequest.setOnClickListener(this);
}

@Override
public void onClick(View v){
if (v.getId()==R.id.send_request){
sendRequestWithHttpURLConnection();
}
}
private void sendRequestWithHttpURLConnection(){
new Thread(new Runnable() {
@Override
public void run() {
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);

connection.setDoInput(true);
connection.setDoOutput(true);
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();
}
}
实在解决不了 求指导
...全文
189 点赞 收藏 3
写回复
3 条回复

还没有回复,快来抢沙发~

发动态
发帖子
Android
创建于2009-10-09

4.6w+

社区成员

9.0w+

社区内容

移动平台 Android
社区公告
暂无公告