android客戶
package com.comingx.xzz; import org.apache.http.HttpResponse;import org.apache.http.client.HttpClient;import org.apache.http.client.methods.HttpPost;import org.apache.http.entity.StringEntity;import org.apache.http.impl.client.DefaultHttpClient;import org.apache.http.util.EntityUtils;import org.json.JSONObject; import android.app.Activity;import android.app.ProgressDialog;import android.os.AsyncTask;import android.os.Bundle;import android.util.Log;import android.view.View;import android.widget.Button;import android.widget.EditText; public class Main extends Activity { private static final String TAG = "Main";private EditText nameEdit;private EditText phoneEdit;private EditText resultEdit;private Button sendBtn;private ProgressDialog progressDialog; @Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main); nameEdit = (EditText) findViewById(R.id.name);phoneEdit = (EditText) findViewById(R.id.phone);resultEdit = (EditText) findViewById(R.id.result);sendBtn = (Button) findViewById(R.id.sendBtn);progressDialog = new ProgressDialog(this); sendBtn.setOnClickListener(new Button.OnClickListener() {@Overridepublic void onClick(View v) {new AT().execute(nameEdit.getText().toString() , phoneEdit.getText().toString());}});}class AT extends AsyncTask{ @Overrideprotected void onPreExecute() {progressDialog.show();} @Overrideprotected String doInBackground(String... params) {try {//請求資料HttpClient hc = new DefaultHttpClient();HttpPost hp = new HttpPost("http://192.168.1.102:8080/JSONServlet/JSONServlet");//請求json報文JSONObject jo = new JSONObject();if (params.length > 1) {jo.put("name", params[0]);jo.put("phone", params[1]);} else {jo.put("err", "error");}Log.d(TAG, "params : " + jo.toString());hp.setEntity(new StringEntity(jo.toString()));HttpResponse hr = hc.execute(hp);String result = null;//擷取返回json報文if(hr.getStatusLine().getStatusCode() == 200){result = EntityUtils.toString(hr.getEntity());Log.d(TAG, "result : " + result);}//關閉串連if (hc != null) {hc.getConnectionManager().shutdown();}return result;} catch (Exception e) {e.printStackTrace();return null;}} @Overrideprotected void onPostExecute(String result) {resultEdit.setText(result);progressDialog.cancel();}}}
伺服器代碼:
package com.comingx.xzz; import java.io.BufferedReader;import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintWriter;import java.util.Enumeration; import javax.servlet.ServletException;import javax.servlet.ServletInputStream;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class JSONServlet */public class JSONServlet extends HttpServlet {private static final long serialVersionUID = 1L; @Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {String result = "";try {/* 讀取資料 */BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream) req.getInputStream(), "utf-8"));StringBuffer sb =new StringBuffer("");String temp;while((temp=br.readLine())!=null){sb.append(temp);}br.close();result = sb.toString();System.out.println("請求報文:" + result);} catch (Exception e) {result = "{err:\"error\"}";} finally {/* 返回資料 */System.out.println("返回報文:" + result);PrintWriter pw = resp.getWriter();pw.write(result);pw.flush();pw.close();}} }
伺服器就只有一個servlet來處理.
代碼很明顯.
android利用的是apache的httpClient來實現網路連接,將json資料儲存與StringEntity中,在設定httpPost的實體setEntity()。利用HttpClient實現網路請求,再擷取資料result = EntityUtils.toStirng(hr.getEntity());最後將結果顯示於Edittext上。
伺服器代碼也很簡單。
利用BufferReader封轉request擷取的InputStream來讀取請求實體,擷取請求json報文,在將報文結果輸出資料流中,返回給用戶端。