android 與servlet json資料互動

來源:互聯網
上載者:User
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報文,在將報文結果輸出資料流中,返回給用戶端。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.