通過GET方式傳遞資料給伺服器
阿新 • • 發佈:2019-01-07
1.web服務端的建立
建立Dynamic Web Project,名稱為ServerGET
2.新建servlet
自動生成的ServerGET.java中有
@WebServlet(“/ServerGET”)
所以web.xml就不需要配置了
3.編寫ServerGET.java
package com.example.servletGet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class ServerGET
*/
@WebServlet("/ServerGET")
public class ServerGET extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ServerGET() {
super();
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("name" );
String age = request.getParameter("age");
System.out.println(name + " " + age);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
}
}
4.測試服務端
5.建立android客戶端
佈局檔案main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.userinformation.MainActivity" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="name:" />
<EditText
android:id="@+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="age:" />
<EditText
android:id="@+id/age"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="save" />
</LinearLayout>
MainActivity.java
package com.example.userinformation;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private EditText nameText, ageText;
private Button button;
private Handler myHandler = new Handler() {
public void handleMessage(Message msg) {
String text = "";
if (msg.what == 1) {
text = "success";
} else if (msg.what == 2){
text = "fail";
}
Toast.makeText(MainActivity.this, text, Toast.LENGTH_SHORT).show();
};
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
nameText = (EditText) findViewById(R.id.name);
ageText = (EditText) findViewById(R.id.age);
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
final String name = nameText.getText().toString();
final String age = ageText.getText().toString();
new Thread(new Runnable() {
@Override
public void run() {
try {
//將EditText中的資料傳到伺服器
boolean result = UserInfoService.save(name, age);
if (result == true) {
myHandler.sendEmptyMessage(1);
} else {
myHandler.sendEmptyMessage(2);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
});
}
}
UserInfoService.java
package com.example.userinformation;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
public class UserInfoService {
public static boolean save(String name, String age) throws Exception {
String path = "http://10.107.56.64:8080/ServerGET/ServerGET";
Map<String, String> params = new HashMap<String, String>();
params.put("name", name);
params.put("age", age);
return sendGETRequest(path, params, "UTF-8");
}
private static boolean sendGETRequest(String path,
Map<String, String> params, String encoding) throws Exception {
StringBuilder sb = new StringBuilder(path);
if (params != null && !params.isEmpty()) {
sb.append("?");
for (Entry<String, String> entry : params.entrySet()) {
sb.append(entry.getKey()).append("=");
sb.append(URLEncoder.encode(entry.getValue(), encoding))
.append("&");
}
sb.deleteCharAt(sb.length() - 1);
}
// 上面的sb用來構造url
HttpURLConnection connection = (HttpURLConnection) new URL(sb.toString())
.openConnection();
connection.setConnectTimeout(5000);
connection.setRequestMethod("GET");
if (connection.getResponseCode() == 200) {
return true;
}
return false;
}
}
測試效果: