如何将数据从Javaservlet发送到android客户端

如何将数据从Javaservlet发送到android客户端,java,android,servlets,Java,Android,Servlets,我正在用android做一个简单的应用程序。android应用程序有一个简单的表单,当我从android客户端单击submit按钮时,表单值会转到servlet。现在我在从servlet到Android客户端获取字符串值时遇到了问题 如何从servlet发送字符串数据?如何在Android客户端中接收字符串数据?您需要建立到servlet页面的URL连接并执行此操作。示例:将下面的代码另存为CustomHttpClient.java import java.io.BufferedReader;

我正在用android做一个简单的应用程序。android应用程序有一个简单的表单,当我从android客户端单击submit按钮时,表单值会转到servlet。现在我在从servlet到Android客户端获取字符串值时遇到了问题


如何从servlet发送字符串数据?如何在Android客户端中接收字符串数据?

您需要建立到servlet页面的URL连接并执行此操作。示例:

将下面的代码另存为CustomHttpClient.java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.ArrayList;

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.conn.params.ConnManagerParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

public class CustomHttpClient {
    /** The time it takes for our client to timeout */
    public static final int HTTP_TIMEOUT = 30 * 1000; // milliseconds

    /** Single instance of our HttpClient */
    private static HttpClient mHttpClient;

    /**
     * Get our single instance of our HttpClient object.
     *
     * @return an HttpClient object with connection parameters set
     */
    private static HttpClient getHttpClient() {
        if (mHttpClient == null) {
            mHttpClient = new DefaultHttpClient();
            final HttpParams params = mHttpClient.getParams();
            HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
            HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
            ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
        }
        return mHttpClient;
    }

    /**
     * Performs an HTTP Post request to the specified url with the
     * specified parameters.
     *
     * @param url The web address to post the request to
     * @param postParameters The parameters to send via the request
     * @return The result of the request
     * @throws Exception
     */
    public static String executeHttpPost(String url, ArrayList<NameValuePair> postParameters) throws Exception {
        BufferedReader in = null;
        try {
            HttpClient client = getHttpClient();
            HttpPost request = new HttpPost(url);
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
            request.setEntity(formEntity);
            HttpResponse response = client.execute(request);
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();

            String result = sb.toString();
            return result;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * Performs an HTTP GET request to the specified url.
     *
     * @param url The web address to post the request to
     * @return The result of the request
     * @throws Exception
     */
    public static String executeHttpGet(String url) throws Exception {
        BufferedReader in = null;
        try {
            HttpClient client = getHttpClient();
            HttpGet request = new HttpGet();
            request.setURI(new URI(url));
            HttpResponse response = client.execute(request);
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();

            String result = sb.toString();
            return result;
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
导入java.io.BufferedReader;
导入java.io.IOException;
导入java.io.InputStreamReader;
导入java.net.URI;
导入java.util.ArrayList;
导入org.apache.http.HttpResponse;
导入org.apache.http.NameValuePair;
导入org.apache.http.client.HttpClient;
导入org.apache.http.client.entity.UrlEncodedFormEntity;
导入org.apache.http.client.methods.HttpGet;
导入org.apache.http.client.methods.HttpPost;
导入org.apache.http.conn.params.ConnManagerParams;
导入org.apache.http.impl.client.DefaultHttpClient;
导入org.apache.http.params.HttpConnectionParams;
导入org.apache.http.params.HttpParams;
公共类CustomHttpClient{
/**客户端超时所需的时间*/
公共静态最终整数HTTP_超时=30*1000;//毫秒
/**我们的HttpClient的单个实例*/
专用静态HttpClient mHttpClient;
/**
*获取HttpClient对象的单个实例。
*
*@返回设置了连接参数的HttpClient对象
*/
私有静态HttpClient getHttpClient(){
if(mHttpClient==null){
mHttpClient=新的DefaultHttpClient();
最终HttpParams params=mHttpClient.getParams();
setConnectionTimeout(参数,HTTP_超时);
HttpConnectionParams.setSoTimeout(参数,HTTP_超时);
setTimeout(参数,HTTP_超时);
}
返回mHttpClient;
}
/**
*使用
*指定的参数。
*
*@param url发布请求的网址
*@param postParameters通过请求发送的参数
*@返回请求的结果
*@抛出异常
*/
公共静态字符串executeHttpPost(字符串url、ArrayList后参数)引发异常{
BufferedReader in=null;
试一试{
HttpClient=getHttpClient();
HttpPost请求=新的HttpPost(url);
UrlEncodedFormEntity formEntity=新的UrlEncodedFormEntity(后参数);
请求。setEntity(formEntity);
HttpResponse response=client.execute(请求);
in=新的BufferedReader(新的InputStreamReader(response.getEntity().getContent());
StringBuffer sb=新的StringBuffer(“”);
字符串行=”;
字符串NL=System.getProperty(“line.separator”);
而((line=in.readLine())!=null){
sb.追加(行+NL);
}
in.close();
字符串结果=sb.toString();
返回结果;
}最后{
if(in!=null){
试一试{
in.close();
}捕获(IOE异常){
e、 printStackTrace();
}
}
}
}
/**
*对指定的url执行HTTP GET请求。
*
*@param url发布请求的网址
*@返回请求的结果
*@抛出异常
*/
公共静态字符串executeHttpGet(字符串url)引发异常{
BufferedReader in=null;
试一试{
HttpClient=getHttpClient();
HttpGet请求=新建HttpGet();
setURI(新的URI(url));
HttpResponse response=client.execute(请求);
in=新的BufferedReader(新的InputStreamReader(response.getEntity().getContent());
StringBuffer sb=新的StringBuffer(“”);
字符串行=”;
字符串NL=System.getProperty(“line.separator”);
而((line=in.readLine())!=null){
sb.追加(行+NL);
}
in.close();
字符串结果=sb.toString();
返回结果;
}最后{
if(in!=null){
试一试{
in.close();
}捕获(IOE异常){
e、 printStackTrace();
}
}
}
}
}
现在,添加要在其中进行客户机-服务器通信的代码

ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
            postParameters.add(new BasicNameValuePair("username",str2));

//here we are passing a variable str2 to the server. 
            String response = null;
try {

//address should be the http address of the server side code.
                    response = CustomHttpClient.executeHttpPost("http://www.xxx.xx/xxx.java", postParameters);
                      String res=response.toString();
                        res= res.replaceAll("\\s+","");


                    //res will be the string that you get from the server. 
ArrayList后参数=新的ArrayList();
添加(新的BasicNameValuePair(“用户名”,str2));
//这里我们将向服务器传递一个变量str2。
字符串响应=null;
试一试{
//地址应该是服务器端代码的http地址。
响应=CustomHttpClient.executeHttpPost(“http://www.xxx.xx/xxx.java“,后参数);
String res=response.toString();
res=res.replaceAll(“\\s+”,”);
//res将是从服务器获取的字符串。

您前面的问题已经回答了这个问题: