从android向servlet发送一个字符串

Posted

技术标签:

【中文标题】从android向servlet发送一个字符串【英文标题】:Send a string to a servlet from android 【发布时间】:2012-12-24 21:37:38 【问题描述】:

我正在尝试将字符串从 android 应用程序发送到 servlet,然后将该字符串检索到我的 android 应用程序,但是当我尝试调用 servlet 时,它会强制关闭我 我不知道为什么(我对 android 很陌生,这对我来说是一个练习) 这是我的 android 简单应用程序:

安卓

package com.theopentutorials.android;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class HttpGetServletActivity extends Activity implements OnClickListener  
    Button button; 
    TextView outputText; 
    public static String request = "kjo ishte e gjitha"; 
    public static final String URL = ("http://10.0.2.2:8080/HttpGetServlet/HelloWorldServlet?param1=" + request); 

    @Override
    public void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        findViewsById();
        button.setOnClickListener(this);
    
    private void findViewsById()  
        button = (Button) findViewById(R.id.button);
        outputText = (TextView) findViewById(R.id.outputTxt);
    
    public void onClick(View view)  
        GetXMLTask task = new GetXMLTask();
        task.execute(new String[]  URL );
    
    private class GetXMLTask extends AsyncTask<String, Void, String> 
        @Override
        protected String doInBackground(String... urls) 
            String output = null;
            for (String url : urls) 
                output = getOutputFromUrl(url);
            
            return output;
        
        private String getOutputFromUrl(String url) 
            StringBuffer output = new StringBuffer("");
            try 
                InputStream stream = getHttpConnection(url);
                BufferedReader buffer = new BufferedReader(
                        new InputStreamReader(stream));
                String s = "";
                while ((s = buffer.readLine()) != null)
                    output.append(s);
             catch (IOException e1) 
                e1.printStackTrace();
            
            return output.toString();
        

        private InputStream getHttpConnection(String urlString)
                throws IOException 
            InputStream stream = null;
            URL url = new URL(urlString);
            URLConnection connection = url.openConnection();
            try 
                HttpURLConnection httpConnection = (HttpURLConnection) connection;
                httpConnection.setRequestMethod("GET");
                httpConnection.connect();

                if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) 
                    stream = httpConnection.getInputStream();
                
             catch (Exception ex) 
                ex.printStackTrace();
            
            return stream;
        
        @Override
        protected void onPostExecute(String output) 
            outputText.setText(output);
        
    

这是我的简单 servlet

伺服器

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;

@WebServlet("/HelloWorldServlet")
public class HelloWorldServlet extends HttpServlet 
    private static final long serialVersionUID = 1L;

    public HelloWorldServlet() 
        super();
    
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response)
            throws ServletException, IOException 
        String par1 =  request.getParameter("param1");
        PrintWriter out = response.getWriter();
        out.println(par1);
    

logcat 日志错误提示

01-10 13:36:50.014: E/AndroidRuntime(1187): FATAL EXCEPTION: AsyncTask #1
01-10 13:36:50.014: E/AndroidRuntime(1187): java.lang.RuntimeException: An error occured while executing doInBackground()
01-10 13:36:50.014: E/AndroidRuntime(1187):     at android.os.AsyncTask$3.done(AsyncTask.java:299)
01-10 13:36:50.014: E/AndroidRuntime(1187):     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
01-10 13:36:50.014: E/AndroidRuntime(1187):     at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
01-10 13:36:50.014: E/AndroidRuntime(1187):     at java.util.concurrent.FutureTask.run(FutureTask.java:239)
01-10 13:36:50.014: E/AndroidRuntime(1187):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
01-10 13:36:50.014: E/AndroidRuntime(1187):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
01-10 13:36:50.014: E/AndroidRuntime(1187):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
01-10 13:36:50.014: E/AndroidRuntime(1187):     at java.lang.Thread.run(Thread.java:856)
01-10 13:36:50.014: E/AndroidRuntime(1187): Caused by: java.lang.NullPointerException: lock == null
01-10 13:36:50.014: E/AndroidRuntime(1187):     at java.io.Reader.<init>(Reader.java:64)
01-10 13:36:50.014: E/AndroidRuntime(1187):     at java.io.InputStreamReader.<init>(InputStreamReader.java:122)
01-10 13:36:50.014: E/AndroidRuntime(1187):     at java.io.InputStreamReader.<init>(InputStreamReader.java:59)
01-10 13:36:50.014: E/AndroidRuntime(1187):     at com.theopentutorials.android.HttpGetServletActivity$GetXMLTask.getOutputFromUrl(HttpGetServletActivity.java:64)
01-10 13:36:50.014: E/AndroidRuntime(1187):     at com.theopentutorials.android.HttpGetServletActivity$GetXMLTask.doInBackground(HttpGetServletActivity.java:54)
01-10 13:36:50.014: E/AndroidRuntime(1187):     at com.theopentutorials.android.HttpGetServletActivity$GetXMLTask.doInBackground(HttpGetServletActivity.java:1)
01-10 13:36:50.014: E/AndroidRuntime(1187):     at android.os.AsyncTask$2.call(AsyncTask.java:287)
01-10 13:36:50.014: E/AndroidRuntime(1187):     at java.util.concurrent.FutureTask.run(FutureTask.java:234)
01-10 13:36:50.014: E/AndroidRuntime(1187):     ... 4 more

有人知道吗? 提前谢谢你的帮助 ! 祝你有美好的一天!

【问题讨论】:

发布你的 logcat 会很有用 感谢您的回复,我刚刚发布了logcat,但我不能很好地理解它 【参考方案1】:

您需要添加互联网访问权限

<uses-permission android:name="android.permission.INTERNET"/>

我发现您应该使用 URLEncoder 对 url 进行编码,因为您的 url 包含空格。请查看http://developer.android.com/reference/java/net/URLEncoder.html

【讨论】:

我已经有了,我尝试直接从 servlet 发送 servlet 响应,就像一个字符串一样,它有效.. 我发现这是由 param1 值中的空格引起的。尝试像 kjoi%20shtegjitha 一样逃避它 我试过像public static final String URL = ("http://10.0.2.2:8080/HttpGetServlet/HelloWorldServlet?param1=CkemiBota");这样的单个词一样发送它,所以不需要urlEncoder但什么都没有,同样的错误:/ 代码在我的环境中运行良好。你能告诉我android SDK版本吗? 4.* 还是 2.*? 你能告诉我你是哪个sdk、平台和tomcat版本吗?这对我有很大帮助!Thnx【参考方案2】:

您忘记在您的 Android 应用中设置 param1。

connection.setRequestProperty("param1", "Your String Value");

然后你会从 Servlet 获取返回值作为响应。

【讨论】:

谢谢你的回复,但我还有2个问题,我不知道我要把这行代码放在哪里,在这之后我想我必须编辑public static final String URL = ("http://10.0.2.2:8080/HttpGetServlet/HelloWorldServlet?param1=" + request);public static final String URL = ("http://10.0.2.2:8080/HttpGetServlet/HelloWorldServlet");对?如果有任何帮助,我也发布了 logcat。 当您设置RequestProperty 时,您将在您的servlet 中获取param1 值,因此您还将获得响应。只需设置requestproperty 行,您就完成了。保持所有其他行不变。

以上是关于从android向servlet发送一个字符串的主要内容,如果未能解决你的问题,请参考以下文章

使用 Retrofit 从 Android 向服务器发送字符串数组

Servlet向客户端发送中文数据的编码情况

通过蓝牙从 Java 服务器向 Android 客户端发送文本

如何正确地通过蓝牙从 Android 向 Arduino 连续发送消息

Servlet表单数据

将字符串从控制台应用程序发送到 Windows 窗体应用程序