您好,登錄后才能下訂單哦!
基于Http的通信
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<String, Void, Void>(){ @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"); } }); } }
通過Get和Post方式請求
<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:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.httpgetdemo.MainActivity" android:orientation="vertical" > <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Username:" /> <EditText android:id="@+id/name" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="text" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="User Age:" /> <EditText android:id="@+id/age" android:layout_width="match_parent" android:layout_height="wrap_content" android:inputType="number" /> <Button android:id="@+id/submit_get" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Submit using GET" /> <Button android:id="@+id/submit_post" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Submit using POST" /> <TextView android:id="@+id/result" android:layout_width="match_parent" android:layout_height="wrap_content" android:textColor="#0000FF" android:textSize="14sp"> </TextView> </LinearLayout >
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); // 創建屬于主線程的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<String, Void, Void>() { @Override protected Void doInBackground(String... params) { System.out.println("mGetClickListener"); Log.i(TAG, "GET request"); // 先獲取用戶名和年齡 String name = mNameText.getText().toString(); String age = mAgeText.getText().toString(); // 使用GET方法發送請求,需要把參數加在URL后面,用?連接,參數之間用&分隔 String url = baseURL + "?username=" + name + "&age=" + age; System.out.println(url); // 生成請求對象 HttpGet httpGet = new HttpGet(url); HttpClient httpClient = new DefaultHttpClient(); // 發送請求 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<String, Void, Void>() { @Override protected Void doInBackground(String... params) { // TODO Auto-generated method stub System.out.println("mPostClickListener"); Log.i(TAG, "POST request"); // 先獲取用戶名和年齡 String name = mNameText.getText().toString(); String age = mAgeText.getText().toString(); NameValuePair pair1 = new BasicNameValuePair( "username", name); NameValuePair pair2 = new BasicNameValuePair("age", age); List<NameValuePair> pairList = new ArrayList<NameValuePair>(); pairList.add(pair1); pairList.add(pair2); try { HttpEntity requestHttpEntity = new UrlEncodedFormEntity( pairList); // URL使用基本URL即可,其中不需要加參數 HttpPost httpPost = new HttpPost(baseURL); // 將請求體內容加入請求中 httpPost.setEntity(requestHttpEntity); // 需要客戶端對象來發送請求 HttpClient httpClient = new DefaultHttpClient(); // 發送請求 // HttpResponse response = httpClient // .execute(httpPost); response = httpClient.execute(httpPost); showResponseResult(response); } catch (Exception e) { e.printStackTrace(); } return null; } }.execute(""); } }); } /** * 顯示響應結果到命令行和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(); } } // 構建Runnable對象,在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("<html><head><title>Welcome!</title></head>"); out.println("<body> Welcome my dear friend!<br>"); out.println("Your name is: " + username + "<br>"); out.println("And your age is: " + age + "</body></html>"); 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"; }// </editor-fold> }
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。