最简略网络通信失败,求原因
最简单网络通信失败,求原因
平板可上网。
在学习安卓开发。想试下最简单的http通信。
现在是以运行,程序就会“很抱歉,HttpGet已经停止运行”自动退出了。
求各位帮忙找出错误,或者给个能成功运行并进行http通信的源码打包!
谢谢!
这是部分代码,下面还有源码打包。有什么疑问可以去看看。
平板可上网。
在学习安卓开发。想试下最简单的http通信。
现在是以运行,程序就会“很抱歉,HttpGet已经停止运行”自动退出了。
求各位帮忙找出错误,或者给个能成功运行并进行http通信的源码打包!
谢谢!
这是部分代码,下面还有源码打包。有什么疑问可以去看看。
package com.example.aa;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
//import android.content.DialogInterface.OnClickListener;
public class MainActivity extends Activity {
private TextView textView;
private Button get,post;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView)findViewById(R.id.textView);
get = (Button)findViewById(R.id.get);
post = (Button)findViewById(R.id.post);
//绑定按钮监听器
get.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//注意:此处ip不能用127.0.0.1或localhost,Android模拟器已将它自己作为了localhost
Toast.makeText(MainActivity.this, "GET", Toast.LENGTH_LONG).show();
String uri = "http://192.168.0.101:80/";
textView.setText(get(uri));
}
});
//绑定按钮监听器
post.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "POST", Toast.LENGTH_LONG).show();
String uri = "http://192.168.0.101:80/";
textView.setText(post(uri));
}
});
}
/**
* 以get方式发送请求,访问web
* @param uri web地址
* @return 响应数据
*/
private static String get(String uri){
BufferedReader reader = null;
StringBuffer sb = null;
String result = "";
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(uri);
try {
//发送请求,得到响应