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了。





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值