Android學習筆記-基于HTTP的通信技術

基于Http的通信

站在用戶的角度思考問題,與客戶深入溝通,找到平鄉(xiāng)網(wǎng)站設計與平鄉(xiāng)網(wǎng)站推廣的解決方案,憑借多年的經(jīng)驗,讓設計與互聯(lián)網(wǎng)技術結合,創(chuàng)造個性化、用戶體驗好的作品,建站類型包括:網(wǎng)站建設、成都網(wǎng)站設計、企業(yè)官網(wǎng)、英文網(wǎng)站、手機端網(wǎng)站、網(wǎng)站推廣、國際域名空間、網(wǎng)頁空間、企業(yè)郵箱。業(yè)務覆蓋平鄉(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<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");
			}
		});
	}

}

Android學習筆記-基于HTTP的通信技術



通過Get和Post方式請求

Android學習筆記-基于HTTP的通信技術

<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);

		// 創(chuàng)建屬于主線程的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方法發(fā)送請求,需要把參數(shù)加在URL后面,用?連接,參數(shù)之間用&分隔
						String url = baseURL + "?username=" + name + "&age=" + age;
						System.out.println(url);
						// 生成請求對象
						HttpGet httpGet = new HttpGet(url);
						HttpClient httpClient = new DefaultHttpClient();
						// 發(fā)送請求
						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即可,其中不需要加參數(shù)
							HttpPost httpPost = new HttpPost(baseURL);
							// 將請求體內容加入請求中
							httpPost.setEntity(requestHttpEntity);
							// 需要客戶端對象來發(fā)送請求
							HttpClient httpClient = new DefaultHttpClient();
							// 發(fā)送請求
							// 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>

}

分享標題:Android學習筆記-基于HTTP的通信技術
當前網(wǎng)址:http://bm7419.com/article22/ijpjcc.html

成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站建設、做網(wǎng)站、App開發(fā)、關鍵詞優(yōu)化、動態(tài)網(wǎng)站、全網(wǎng)營銷推廣

廣告

聲明:本網(wǎng)站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經(jīng)允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)

小程序開發(fā)