android http 本地 web服务(tomcat)
1. Android代码
01
<b>public class JobActivity extends Activity {
02
private TextView show;
03
private EditText txt;
04
private Button btn;
05
06
/** Called when the activity is first created. */
07
@Override
08
public void onCreate(Bundle savedInstanceState) {
09
super.onCreate(savedInstanceState);
10
setContentView(R.layout.main);
11
12
ConnectivityManager con=(ConnectivityManager)getSystemService(Activity.CONNECTIVITY_SERVICE);
13
boolean wifi=con.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting();
14
boolean internet=con.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnectedOrConnecting();
15
if(wifi ){
16
show = (TextView)findViewById(R.id.show);
17
txt = (EditText)findViewById(R.id.txt);
18
btn = (Button)findViewById(R.id.btn);
19
btn.setOnClickListener(new OnClickListener() {
20
@Override
21
public void onClick(View v) {
22
show.setText("dianjile");
23
dopost(txt.getText().toString());
24
}
25
});
26
}
27
}
28
29
private void dopost(String val){
30
//封装数据
31
Map<String, String> parmas = new HashMap<String, String>();
32
parmas.put("name", val);
33
</b><p><b> DefaultHttpClient client = new DefaultHttpClient();//http客户端</b></p>
34
<p><b> //这个地方需要注意:如果是调试器 </b><span style="color:#ff0000;font-family:verdana, 'ms song', 宋体, Arial, 微软雅黑, Helvetica, sans-serif;text-align:left;white-space:normal;background-color:#ffffff;">10.0.2.2 本机地址;真机上:则是路由器中电脑地址</span></p>
35
<b> HttpPost httpPost = new HttpPost("http://192.168.2.100:80/loowj/android$Android$go");
36
ArrayList<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>();
37
if(parmas != null){
38
Set<String> keys = parmas.keySet();
39
for(Iterator<String> i = keys.iterator(); i.hasNext();) {
40
String key = (String)i.next();
41
pairs.add(new BasicNameValuePair(key, parmas.get(key)));
42
}
43
}
44
45
try {
46
UrlEncodedFormEntity p_entity = new UrlEncodedFormEntity(pairs, "utf-8");
47
/*
48
* 将POST数据放入HTTP请求
49
*/
50
httpPost.setEntity(p_entity);
51
/*
52
* 发出实际的HTTP POST请求
53
*/
54
TextView tv = (TextView)findViewById(R.id.state);
55
tv.setText("start post:");
56
HttpResponse response = client.execute(httpPost);
57
tv.setText((response.getStatusLine().getStatusCode() +""));
58
59
HttpEntity entity = response.getEntity();
60
InputStream content = entity.getContent();
61
String returnConnection = convertStreamToString(content);
62
show.setText(returnConnection);
63
} catch (IllegalStateException e) {
64
e.printStackTrace();
65
} catch (IOException e) {
66
e.printStackTrace();
67
}
68
}
69
70
private String convertStreamToString(InputStream is) {
71
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
72
StringBuilder sb = new StringBuilder();
73
String line = null;
74
try {
75
while ((line = reader.readLine()) != null) {
76
sb.app
补充:移动开发 , Android ,