基于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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。