基于Http的通信
站在用戶(hù)的角度思考問(wèn)題,與客戶(hù)深入溝通,找到平鄉(xiāng)網(wǎng)站設(shè)計(jì)與平鄉(xiāng)網(wǎng)站推廣的解決方案,憑借多年的經(jīng)驗(yàn),讓設(shè)計(jì)與互聯(lián)網(wǎng)技術(shù)結(jié)合,創(chuàng)造個(gè)性化、用戶(hù)體驗(yàn)好的作品,建站類(lèi)型包括:網(wǎng)站建設(shè)、成都網(wǎng)站設(shè)計(jì)、企業(yè)官網(wǎng)、英文網(wǎng)站、手機(jī)端網(wǎng)站、網(wǎng)站推廣、國(guó)際域名空間、網(wǎng)頁(yè)空間、企業(yè)郵箱。業(yè)務(wù)覆蓋平鄉(xiāng)地區(qū)。
package com.example.httpgetdemo; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViewById(R.id.button1).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new AsyncTask(){ @Override protected Void doInBackground(String... params) { try { URL url = new URL(params[0]); URLConnection connection = url.openConnection(); InputStream inputStream = connection.getInputStream(); InputStreamReader isr = new InputStreamReader(inputStream, "utf-8"); BufferedReader br = new BufferedReader(isr); String line; while ((line = br.readLine()) != null) { System.out.println(line); } br.close(); isr.close(); inputStream.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } }.execute("http://fanyi.youdao.com/openapi.do?keyfrom=httpgetdemo1&key=1659546208&type=data&doctype=json&version=1.1&q=good"); } }); } }
通過(guò)Get和Post方式請(qǐng)求
MainActivity.java
package com.example.httpgetdemo; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import android.app.Activity; import android.os.AsyncTask; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends Activity { private String TAG = "http"; private String baseURL = "http://192.168.24.250:8084/test_web/NewServlet"; private EditText mNameText = null; private EditText mAgeText = null; private HttpResponse response = null; private Button getButton = null; private Button postButton = null; private TextView mResult = null; private Handler handler = null; private String result = ""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 創(chuàng)建屬于主線(xiàn)程的handler handler = new Handler(); mNameText = (EditText) findViewById(R.id.name); mAgeText = (EditText) findViewById(R.id.age); mResult = (TextView) findViewById(R.id.result); getButton = (Button) findViewById(R.id.submit_get); getButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new AsyncTask() { @Override protected Void doInBackground(String... params) { System.out.println("mGetClickListener"); Log.i(TAG, "GET request"); // 先獲取用戶(hù)名和年齡 String name = mNameText.getText().toString(); String age = mAgeText.getText().toString(); // 使用GET方法發(fā)送請(qǐng)求,需要把參數(shù)加在URL后面,用?連接,參數(shù)之間用&分隔 String url = baseURL + "?username=" + name + "&age=" + age; System.out.println(url); // 生成請(qǐng)求對(duì)象 HttpGet httpGet = new HttpGet(url); HttpClient httpClient = new DefaultHttpClient(); // 發(fā)送請(qǐng)求 try { // HttpResponse response = // httpClient.execute(httpGet); response = httpClient.execute(httpGet); // handler.post(runnableUi); System.out.println("response:" + response); showResponseResult(response); } catch (Exception e) { e.printStackTrace(); } return null; } }.execute(""); } }); postButton = (Button) findViewById(R.id.submit_post); postButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub new AsyncTask () { @Override protected Void doInBackground(String... params) { // TODO Auto-generated method stub System.out.println("mPostClickListener"); Log.i(TAG, "POST request"); // 先獲取用戶(hù)名和年齡 String name = mNameText.getText().toString(); String age = mAgeText.getText().toString(); NameValuePair pair1 = new BasicNameValuePair( "username", name); NameValuePair pair2 = new BasicNameValuePair("age", age); List pairList = new ArrayList (); pairList.add(pair1); pairList.add(pair2); try { HttpEntity requestHttpEntity = new UrlEncodedFormEntity( pairList); // URL使用基本URL即可,其中不需要加參數(shù) HttpPost httpPost = new HttpPost(baseURL); // 將請(qǐng)求體內(nèi)容加入請(qǐng)求中 httpPost.setEntity(requestHttpEntity); // 需要客戶(hù)端對(duì)象來(lái)發(fā)送請(qǐng)求 HttpClient httpClient = new DefaultHttpClient(); // 發(fā)送請(qǐng)求 // HttpResponse response = httpClient // .execute(httpPost); response = httpClient.execute(httpPost); showResponseResult(response); } catch (Exception e) { e.printStackTrace(); } return null; } }.execute(""); } }); } /** * 顯示響應(yīng)結(jié)果到命令行和TextView * * @param response */ private void showResponseResult(HttpResponse response) { System.out.println("response:" + response); if (null == response) { return; } HttpEntity httpEntity = response.getEntity(); try { InputStream inputStream = httpEntity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader( inputStream)); String line = ""; while (null != (line = reader.readLine())) { result += line; } // System.out.println(result); // mResult.setText("Response Content from server: " + result); MainActivity.this.runOnUiThread(runnableUi); } catch (Exception e) { e.printStackTrace(); } } // 構(gòu)建Runnable對(duì)象,在runnable中更新界面 Runnable runnableUi = new Runnable() { @Override public void run() { // 更新界面 mResult.setText("Response Content from server: " + result); result = ""; } }; }
Server端代碼
import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author Administrator */ @WebServlet(urlPatterns = {"/NewServlet"}) public class NewServlet extends HttpServlet { protected void proce***equest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); String username = request.getParameter("username"); String age = request.getParameter("age"); response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("Welcome! "); out.println(" Welcome my dear friend!
"); out.println("Your name is: " + username + "
"); out.println("And your age is: " + age + ""); out.flush(); out.close(); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.err.println("doGet"); proce***equest(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.err.println("doPost"); proce***equest(request, response); } @Override public String getServletInfo() { return "Short description"; }// }