RELATEED CONSULTING
相关咨询
选择下列产品马上在线沟通
服务时间:24小时服务
你可能遇到了下面的问题
关闭右侧工具栏
android和web服务器网络的通信方式

  客户端建立:

Http_androidActivity.java代码

复制代码
 1 package com.example.newsmanage;
 2 import android.app.Activity;
 3 import android.os.Bundle;
 4 
 5 public class Http_androidActivity extends Activity {
 6     /** Called when the activity is first created. */
 7     @Override
 8     public void onCreate(Bundle savedInstanceState) {
 9 
10         super.onCreate(savedInstanceState);
11         setContentView(R.layout.main);
12     }
13 }
复制代码

NewsManageActivity.java代码

复制代码
 1 package com.example.newsmanage;
 2 
 3 import com.example.service.NewsService;
 4 import android.app.Activity;
 5 import android.os.Bundle;
 6 import android.view.View;
 7 import android.widget.Button;
 8 import android.widget.EditText;
 9 import android.widget.Toast;
10 
11 public class NewsManageActivity extends Activity {
12     /** Called when the activity is first created. */
13  EditText titleText;
14  EditText lengthText;
15  Button button;
16 
17     @Override
18     public void onCreate(Bundle savedInstanceState) {
19 
20         super.onCreate(savedInstanceState);
21         setContentView(R.layout.main);     
22 
23         titleText = (EditText) this.findViewById(R.id.title);
24         lengthText = (EditText) this.findViewById(R.id.timelength);
25         button = (Button) this.findViewById(R.id.button);
26     }
27 
28     public void save(View v) throws Exception{
29 
30      String title = titleText.getText().toString();
31      String timelength = lengthText.getText().toString();
32 
33      boolean result = NewsService.save(title,timelength);
34 
35      if(result){
36 
37       Toast.makeText(getApplicationContext(), R.string.success, Toast.LENGTH_LONG).show();
38 
39      } else {
40       Toast.makeText(getApplicationContext(), R.string.fail, Toast.LENGTH_LONG).show();
41      }
42     }
43 }
复制代码

NewsService.java代码

复制代码
package com.example.service;

import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

public class NewsService {
 /**

  * 保存数据,传递参数给web服务器端

  * @param title 标题

  * @param timelength 时长

  * @return

  */

 public static boolean save(String title, String timelength) throws Exception {

  //119.119.228.5为本机IP地址,不能用localhost代替

  String path = "http://192.168.1.5:8080/http_service/servlet";

  Map<String,String> params = new HashMap<String,String>();

  params.put("title", title);

  params.put("timelength", timelength);

  //get请求方式

  return sendGETRequest(path,params,"UTF-8");

  //post请求方式

  //return sendPOSTRequest(path,params,"UTF-8");

  //httpClient请求方式,如果单纯传递参数的话建议使用GET或者POST请求方式

  //return sendHttpClientPOSTRequest(path,params,"UTF-8");//httpclient已经集成在android中

 }

 /**

  * 通过HttpClient发送post请求

  * @param path

  * @param params

  * @param encoding

  * @return

  * @throws Exception

  */

 private static boolean sendHttpClientPOSTRequest(String path,

   Map<String, String> params, String encoding) throws Exception {

  List<NameValuePair> pairs = new ArrayList<NameValuePair>();//存放请求参数

  for(Map.Entry<String, String> entry:params.entrySet()){

   pairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));

  }

  //防止客户端传递过去的参数发生乱码,需要对此重新编码成UTF-8

  UrlEncodedFormEntity entity = new UrlEncodedFormEntity(pairs,encoding);

  HttpPost httpPost = new HttpPost(path);

  httpPost.setEntity(entity);

  DefaultHttpClient client = new DefaultHttpClient();

  HttpResponse response = client.execute(httpPost);

  if(response.getStatusLine().getStatusCode() == 200){

   return true;

  }

  return false;

 }

 /**

  * 放松post请求

  * @param path 请求路径

  * @param params 请求参数

  * @param encoding 编码

  * @return 请求是否成功

  */

 private static boolean sendPOSTRequest(String path,

   Map<String, String> params, String encoding) throws Exception{

  StringBuilder data = new StringBuilder(path);

  for(Map.Entry<String, String> entry:params.entrySet()){

  data.append(entry.getKey()).append("=");

   //防止客户端传递过去的参数发生乱码,需要对此重新编码成UTF-8

  data.append(URLEncoder.encode(entry.getValue(),encoding));

   data.append("&");

  }

  data.deleteCharAt(data.length() - 1);

  byte[] entity = data.toString().getBytes();//得到实体数据

  HttpURLConnection conn = (HttpURLConnection) new URL(path).openConnection();

  conn.setConnectTimeout(5000);

  conn.setRequestMethod("POST");

  conn.setDoOutput(true);//设置为允许对外输出数据


 conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

 conn.setRequestProperty("Content-Length", String.valueOf(entity.length));


  OutputStream outStream = conn.getOutputStream();

  outStream.write(entity);//写到缓存


  if(conn.getResponseCode()==200){//只有取得服务器返回的http协议的任何一个属性时才能把请求发送出去

   return true;

  }

  return false;

 }

 /**

  * 发送GET请求

  * @param path 请求路径

  * @param params 请求参数

  * @return 请求是否成功

  * @throws Exception

  */

 private static boolean sendGETRequest(String path,

   Map<String, String> params,String encoding) throws Exception {

  StringBuilder url = new StringBuilder(path);

  url.append("?");

  for(Map.Entry<String, String> entry:params.entrySet()){

  url.append(entry.getKey()).append("=");

   //get方式请求参数时对参数进行utf-8编码,URLEncoder

   //防止客户端传递过去的参数发生乱码,需要对此重新编码成UTF-8

  url.append(URLEncoder.encode(entry.getValue(), encoding));

   url.append("&");

  }

  url.deleteCharAt(url.length()-1);

  HttpURLConnection conn = (HttpURLConnection) new URL(url.toString()).openConnection();

  conn.setConnectTimeout(5000);

  conn.setRequestMethod("GET");

  if(conn.getResponseCode() == 200){

   return true;

  }

  return false;

 }

}
复制代码

Main.xml代码如下

复制代码
 1 <?xml version="1.0" encoding="utf-8"?>
 2 
 3 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 4 
 5     android:layout_width="fill_parent"
 6 
 7     android:layout_height="fill_parent"
 8 
 9     android:orientation="vertical" >
10 
11  
12 
13    <TextView
14 
15         android:layout_width="fill_parent"
16 
17         android:layout_height="wrap_content"
18 
19         android:text="@string/title" />
20 
21  
22 
23    <EditText
24 
25         android:id="@+id/title"
26 
27         android:layout_width="fill_parent"
28 
29         android:layout_height="wrap_content" >
30 
31  
32 
33         <requestFocus />
34 
35    </EditText>
36 
37  
38 
39    <TextView
40 
41         android:id="@+id/textView1"
42 
43         android:layout_width="fill_parent"
44 
45         android:layout_height="wrap_content"
46 
47         android:text="@string/timelength" />
48 
49  
50 
51    <EditText
52 
53         android:id="@+id/timelength"
54 
55         android:layout_width="fill_parent"
56 
57         android:layout_height="wrap_content" android:numeric="integer"/>
58 
59  
60 
61    <Button
62 
63         android:id="@+id/button"
64 
65         android:layout_width="wrap_content"
66 
67         android:layout_height="wrap_content"
68 
69         android:text="@string/button" android:onClick="save"/>
70 
71  
72 
73 </LinearLayout>
复制代码

AndroidManifest.xml代码如下

复制代码
 1 <?xml version="1.0" encoding="utf-8"?>
 2 
 3 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
 4 
 5     package="com.example.newsmanage"
 6 
 7     android:versionCode="1"
 8 
 9     android:versionName="1.0" >
10 
11  
12 
13    <uses-sdk android:minSdkVersion="7" />
14 
15  
16 
17    <application
18 
19         android:icon="@drawable/ic_launcher"
20 
21         android:label="@string/app_name" >
22 
23         <activity
24 
25            android:name=".NewsManageActivity"
26 
27            android:label="@string/app_name" >
28 
29             <intent-filter>
30 
31                 <action android:name="android.intent.action.MAIN" />
32 
33  
34 
35                 <category android:name="android.intent.category.LAUNCHER" />
36 
37             </intent-filter>
38 
39         </activity>
40 
41    </application>
42 
43  <uses-permission android:name="android.permission.INTERNET"/>
44 
45    
46 
47 </manifest>