Android与服务器http连接模块代码
16lz
2021-01-26
1 package com.example.httpdemo2; 2 3 import java.io.BufferedReader; 4 import java.io.IOException; 5 import java.io.InputStream; 6 import java.io.InputStreamReader; 7 import java.io.UnsupportedEncodingException; 8 import java.util.ArrayList; 9 import java.util.List; 10 11 import org.apache.http.HttpEntity; 12 import org.apache.http.HttpResponse; 13 import org.apache.http.NameValuePair; 14 import org.apache.http.client.HttpClient; 15 import org.apache.http.client.entity.UrlEncodedFormEntity; 16 import org.apache.http.client.methods.HttpGet; 17 import org.apache.http.client.methods.HttpPost; 18 import org.apache.http.impl.client.DefaultHttpClient; 19 import org.apache.http.message.BasicNameValuePair; 20 21 import android.os.Bundle; 22 import android.app.Activity; 23 import android.util.Log; 24 import android.view.Menu; 25 import android.view.View; 26 import android.view.View.OnClickListener; 27 import android.widget.Button; 28 import android.widget.EditText; 29 import android.widget.TextView; 30 31 public class HttpDemo2Activity extends Activity 32 { 33 private String TAG = "http"; 34 private EditText mNameText = null; 35 private EditText mAgeText = null; 36 37 private Button getButton = null; 38 private Button postButton = null; 39 40 private TextView mResult = null; 41 42 // 基本地址:服务器ip地址:端口号/Web项目逻辑地址+目标页面(Servlet)的url-pattern 43 private String baseURL = "http://192.168.11.6:8080/HelloWeb/servlet/WelcomeUserServlet"; 44 45 @Override 46 protected void onCreate(Bundle savedInstanceState) 47 { 48 Log.i(TAG, "onCreate"); 49 super.onCreate(savedInstanceState); 50 setContentView(R.layout.activity_http_demo2); 51 52 mNameText = (EditText) findViewById(R.id.name); 53 mAgeText = (EditText) findViewById(R.id.age); 54 mResult = (TextView) findViewById(R.id.result); 55 56 getButton = (Button) findViewById(R.id.submit_get); 57 getButton.setOnClickListener(mGetClickListener); 58 postButton = (Button) findViewById(R.id.submit_post); 59 postButton.setOnClickListener(mPostClickListener); 60 } 61 62 private OnClickListener mGetClickListener = new View.OnClickListener() 63 { 64 65 @Override 66 public void onClick(View v) 67 { 68 Log.i(TAG, "GET request"); 69 // 先获取用户名和年龄 70 String name = mNameText.getText().toString(); 71 String age = mAgeText.getText().toString(); 72 73 // 使用GET方法发送请求,需要把参数加在URL后面,用?连接,参数之间用&分隔 74 String url = baseURL + "?username=" + name + "&age=" + age; 75 76 // 生成请求对象 77 HttpGet httpGet = new HttpGet(url); 78 HttpClient httpClient = new DefaultHttpClient(); 79 80 // 发送请求 81 try 82 { 83 84 HttpResponse response = httpClient.execute(httpGet); 85 86 // 显示响应 87 showResponseResult(response);// 一个私有方法,将响应结果显示出来 88 89 } 90 catch (Exception e) 91 { 92 e.printStackTrace(); 93 } 94 95 } 96 }; 97 98 private OnClickListener mPostClickListener = new View.OnClickListener() 99 {100 101 @Override102 public void onClick(View v)103 {104 Log.i(TAG, "POST request");105 // 先获取用户名和年龄106 String name = mNameText.getText().toString();107 String age = mAgeText.getText().toString();108 109 NameValuePair pair1 = new BasicNameValuePair("username", name);110 NameValuePair pair2 = new BasicNameValuePair("age", age);111 112 List<NameValuePair> pairList = new ArrayList<NameValuePair>();113 pairList.add(pair1);114 pairList.add(pair2);115 116 try117 {118 HttpEntity requestHttpEntity = new UrlEncodedFormEntity(119 pairList);120 // URL使用基本URL即可,其中不需要加参数121 HttpPost httpPost = new HttpPost(baseURL);122 // 将请求体内容加入请求中123 httpPost.setEntity(requestHttpEntity);124 // 需要客户端对象来发送请求125 HttpClient httpClient = new DefaultHttpClient();126 // 发送请求127 HttpResponse response = httpClient.execute(httpPost);128 // 显示响应129 showResponseResult(response);130 }131 catch (Exception e)132 {133 e.printStackTrace();134 }135 136 }137 };138 139 /**140 * 显示响应结果到命令行和TextView141 * @param response142 */143 private void showResponseResult(HttpResponse response)144 {145 if (null == response)146 {147 return;148 }149 150 HttpEntity httpEntity = response.getEntity();151 try152 {153 InputStream inputStream = httpEntity.getContent();154 BufferedReader reader = new BufferedReader(new InputStreamReader(155 inputStream));156 String result = "";157 String line = "";158 while (null != (line = reader.readLine()))159 {160 result += line;161 162 }163 164 System.out.println(result);165 mResult.setText("Response Content from server: " + result);166 }167 catch (Exception e)168 {169 e.printStackTrace();170 }171 172 }173 174 }
布局文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical" ><TextViewandroid:layout_width="match_parent"android:layout_height="wrap_content"android:text="Username:" /><EditTextandroid:id="@+id/name"android:layout_width="match_parent"android:layout_height="wrap_content"android:inputType="text" /><TextViewandroid:layout_width="match_parent"android:layout_height="wrap_content"android:text="User Age:" /><EditTextandroid:id="@+id/age"android:layout_width="match_parent"android:layout_height="wrap_content"android:inputType="number" /><Buttonandroid:id="@+id/submit_get"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="Submit using GET" /><Buttonandroid:id="@+id/submit_post"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="Submit using POST" /><TextViewandroid:id="@+id/result"android:layout_width="match_parent"android:layout_height="wrap_content"android:textColor="#0000FF"android:textSize="14sp" ></TextView></LinearLayout>
须在androidMenifest中配置联网权限;
更多相关文章
- android中获取手机短信,删除短信功能
- Android(安卓)WebView请求,保存cookie,判断登录状态
- Android6.0+权限申请工具类PermissionUtil
- 使用HttpURLConnection请求数据、上传文件、图片等
- viewModel与recyclerView结合
- Android-HttpsURLConnectionHelp工具类
- Android短信发送程序核心代码
- Android实现点击切换视图并跳转传值
- 王学岗OKHttp下载图片