一个登录系统,安卓客户端接收不到本地服务器传递过来的数据

sunny冰青 发布于 2015/02/15 12:38
阅读 1K+
收藏 0

android 客户端程序

public class MainActivity extends Activity 

{
private EditText editText_name, editText_age;
private Button button_get, button_post;
private String baseUrl = "http://localhost:8080/HttpWebServerDemo1/123";
private String str_name, str_age,str_line = "",str_result = "";
private HttpResponse httpResponse;
private HttpPost httpPost;
private HttpClient httpClient;
private HttpEntity httpEntity;
private InputStream inputStream;
private BufferedReader bufferedReader;
@Override
protected void onCreate(Bundle savedInstanceState) 
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText_name = (EditText)findViewById(R.id.editText_name);
editText_age = (EditText)findViewById(R.id.editText_age);
button_get =  (Button)findViewById(R.id.button_get);
button_post = (Button)findViewById(R.id.button_post);
str_name = editText_name.getText().toString();
str_age = editText_age.getText().toString();
button_get.setOnClickListener(new OnClickListener()
{



public void onClick(View v) 
{
String  url = baseUrl + "?" + "name=" + str_name + "&age=" + str_age;
HttpGet httpGet = new HttpGet(url);//创建请求对象;
httpClient = new DefaultHttpClient();//创建http客户端对象;
try 
{
httpResponse = httpClient.execute(httpGet);//使用http客户端执行响应;
httpEntity = httpResponse.getEntity();
inputStream = httpEntity.getContent();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
while((str_line = bufferedReader.readLine())!=null)
{
str_result += str_line;
}
//System.out.println(str_result);
Toast.makeText(MainActivity.this, str_result, Toast.LENGTH_LONG).show();//str_result获得返回值

catch (ClientProtocolException e) 
{

e.printStackTrace();

catch (IOException e) 
{

e.printStackTrace();
}
}

});

}

}

AndroidManifest.xml文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.httpdemo1"
    android:versionCode="1"
    android:versionName="1.0" >


    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />


                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>


</manifest>
服务端程序
public class TestServlet extends HttpServlet 
{
private static final long serialVersionUID = 1L;


protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
{
String name = request.getParameter("name");
String age = request.getParameter("age");
out.println("使用Get方法发送请求,我的名字是"+name+"我的年龄是"+age);
}
web.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" 
    id="WebApp_ID" version="3.0">
 
  <servlet>
      <servlet-name>TestServlet</servlet-name>
      <servlet-class>com.demo1.TestServlet</servlet-class>
  </servlet>
  <servlet-mapping>
      <servlet-name>TestServlet</servlet-name>
      <url-pattern>/123</url-pattern>
  </servlet-mapping>
 
</web-app>

加载中
0
cyper
cyper

刚好在学习Android开发, 回答下这个问题测试一下我的学习成果

  1. Servlet的名字取得很奇葩,很少见用数字123做为servlet的名字的, 代码的可读性大打折扣.

  2. localhost指向的是手机本身或是模拟器本身,你的tomcat服务肯定不是部署在模拟器或手机上, 如果你是用的模拟器, 则必须把localhost改成10.0.2.2

  3. 当你的tomcat服务启动后,不要急于在手机上做测试, 你应该在浏览器上打开http://localhost:8080/HttpWebServerDemo1/123?name=cyper&age=20看看响应是否正常. 因为你的servlet中有中文,至少你得加上如下代码:

    response.addHeader("Content-Type","text/plain;charset=UTF-8");
  4. 修改后的servlet代码如下:

    String name = request.getParameter("name"); String age = request.getParameter("age"); response.addHeader("Content-Type","text/plain;charset=UTF-8");
    PrintWriter out = response.getWriter();
    out.println("使用Get方法发送请求,我的名字是" + name + "我的年龄是" + age);
  5. 从3.0开始,在UI线程中做network i/o是不允许的,参考so, 你必须使用new Thread + Handler或AsynTask, 否则会报android.os.NetworkOnMainThreadException

  6. 你必须在manifest文件中声明使用INTERNET的权限.

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

    否则会报java.net.SocketException: socket failed: EACCES (Permission denied)

  7. 完整代码见git osc

s
sunny冰青
使用纯英文是正常的,你说的那个我加了
cyper
cyper
回复 @sunny冰青 : 使用纯英文现在正常吗?中文乱码的问题可以慢慢慢解决.你有加Content-Type这个header?你在浏览器中打开也有乱码? 如果在手机端打开有乱码,你需要和我一样,设定EntityUtils.toString的第二个参数为utf-8
s
sunny冰青
按照你说的设置了之后还是有乱码
0
寒情漠漠
寒情漠漠

网络操作放在新线程中

不要在UI线程中,使用handler通知

s
sunny冰青
额,这个是按照mars的视频做的,不用单独开一个线程也能做出来吧,难道是我的服务端搭建的有问题
0
plugin
plugin
上面说的是对的。网络操作要在单独的线程中,你看的那个mars视频,他是以2.3的系统讲的。那个时候是可以这么做的。但是以后的不行
s
sunny冰青
谢谢
0
cyper
cyper
android studio建的工程目录结构太深,其实就一个类, 代码如下:

public class MainActivity extends Activity {
    private EditText nameText;
    private EditText ageText;
    private Button btnSend;

    private String baseUrl = "http://10.0.2.2:8080/HttpWebServerDemo1/123";

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            String response = (String) msg.obj;
            Toast.makeText(MainActivity.this, response, Toast.LENGTH_LONG).show();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        nameText = (EditText) findViewById(R.id.name);
        ageText = (EditText) findViewById(R.id.age);
        btnSend = (Button) findViewById(R.id.send);

        btnSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                final String name = nameText.getText().toString();
                final String age = ageText.getText().toString();

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        String url = String.format("%s?name=%s&age=%s", baseUrl, name, age);
                        HttpGet httpGet = new HttpGet(url);
                        HttpClient httpClient = new DefaultHttpClient();
                        try {
                            HttpResponse httpResponse = httpClient.execute(httpGet);
                            HttpEntity httpEntity = httpResponse.getEntity();
                            String str_result = EntityUtils.toString(httpEntity, "utf-8");
                            Message message = new Message();
                            message.obj = str_result;
                            handler.sendMessage(message);

                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }).start();
            }
        });
    }


}




返回顶部
顶部