Android 設備從 Server獲取文本


  • 環境搭建

JDK、Tomcat、Eclipse 暫略

  • 服務端實現

服務端簡單實現一個Servlet,部署在Tomcat上。

package com.ltc.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class Hello
 */
public class Hello extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * Default constructor. 
     */
    public Hello() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html");
		
		
		PrintWriter out = response.getWriter();
		out.println("Hello, world! by servlet hello ");
		out.flush();
		out.close();
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}


  • 客戶端實現

客戶端主要用HttpClient實現網絡請求

package com.ltc.httpclient.demo;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
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 org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class HttpClientDemoActivity extends Activity {
	
	private TextView msgTextView;

	private Button getButton;
	private Button postButton;
	
	private String URL = "http://10.18.100.30:8080/hello/Hello";
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        msgTextView = (TextView)findViewById(R.id.msg_textview);
        
        //get
        getButton = (Button)findViewById(R.id.get_button);
        getButton.setOnClickListener(new Button.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				msgTextView.setText("");
				
				String uri = URL;
				HttpGet httpRequest = new HttpGet(uri);
				try {
					
					HttpParams httpParameters = new BasicHttpParams();
					// Set the timeout in milliseconds until a connection is established.
					// The default value is zero, that means the timeout is not used. 
					int timeoutConnection = 3000;
					HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
					// Set the default socket timeout (SO_TIMEOUT) 
					// in milliseconds which is the timeout for waiting for data.
					int timeoutSocket = 5000;
					HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

					DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
					httpClient.setParams(httpParameters);
					HttpResponse httpResponse = httpClient.execute(httpRequest);
					
					if(httpResponse.getStatusLine().getStatusCode() == 200) {
						String strResult = EntityUtils.toString(httpResponse.getEntity());
						strResult = eregiReplace("(\r|\n|\r\n|\n\r)", "", strResult);
						msgTextView.setText(strResult + httpResponse.getParams().toString());
					} else {
						msgTextView.setText("Get Error: " + httpResponse.getStatusLine().getStatusCode());
					}
				} catch (ClientProtocolException e) {
					msgTextView.setText("ClientProtocolException : " + e.getMessage().toString());
				} catch (IOException e) {
					msgTextView.setText("IOException : " + e.getMessage().toString());
				} catch (Exception e) {
					msgTextView.setText("Exception : " + e.getMessage().toString());
				}
				
			}
		});
        
        //post
        postButton = (Button)findViewById(R.id.post_button);
        postButton.setOnClickListener(new Button.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				msgTextView.setText("");

				String uri = URL;
				HttpPost httpRequest = new HttpPost(uri);
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				params.add(new BasicNameValuePair("bookname", "china"));
				try {
					httpRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
					
					HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequest);
					
					if(httpResponse.getStatusLine().getStatusCode() == 200) {
						String strResult = EntityUtils.toString(httpResponse.getEntity());
						msgTextView.setText(strResult);
					} else {
						msgTextView.setText("Post Error: " + httpResponse.getStatusLine().getStatusCode());
					}
				} catch (ClientProtocolException e) {
					msgTextView.setText("ClientProtocolException : " + e.getMessage().toString());
				} catch (IOException e) {
					msgTextView.setText("IOException : " + e.getMessage().toString());
				} catch (Exception e) {
					msgTextView.setText("Exception : " + e.getMessage().toString());
				}
			}
		});
    }
	
	/**
	 * 替換指定字符串 <br>
	 * 
	 * @param strFrom
	 * @param strTo
	 * @param strTarget
	 * @return
	 */
	public String eregiReplace(String strFrom, String strTo, String strTarget) {
		String strPattern = "(?i)" + strFrom;
		Pattern p = Pattern.compile(strPattern);
		Matcher m = p.matcher(strTarget);
		if(m.find()) {
			return strTarget.replaceAll(strFrom, strTo);
		} else {
			return strTarget;
		}
	}
	
	public String clearSpecialChar(String s) {
		Pattern pattern = Pattern.compile("\\s|\\r|\\n|\\t");
		Matcher matcher = pattern.matcher(s);
		return matcher.replaceAll("").trim();
	}
}


點擊post按鈕



點擊post 按鈕

後續就是添加請求的參數,返回結果用json格式,定義API了。





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章