如何连接到从Android应用程序的servlet? [英] How to connect to servlet from android app?

查看:132
本文介绍了如何连接到从Android应用程序的servlet?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让同该servlet的连接的应用程序。调试器不显示任何错误,无论是servlet有任何错误,但仍然code不工作
这是Android应用程序My_appActivity.java

 包com.m_app.first_app;进口java.io.DataInputStream中;
进口java.io.DataOutputStream中;
进口的java.io.InputStream;
进口java.io.OutputStream中;
进口java.net.HttpURLConnection中;
进口的java.net.URL;进口com.m_app.first_app.R;
进口android.app.Activity;
进口android.os.Bundle;
进口android.util.Log;
进口android.view.View;
进口android.widget.Button;
进口android.widget.EditText;公共类My_appActivity延伸活动{
    公共静态最后的字符串标记=SearchRecord;
    私人的EditText mEditText1;
    私人按钮mButton1;    @覆盖
    公共无效的onCreate(捆绑冰柱)
    {
        Log.v(TAG活动状态:的onCreate());
        super.onCreate(冰柱);
        的setContentView(R.layout.main);     //获取手柄UI对象
        mEditText1 =(EditText上)findViewById(R.id.editText1);
        mButton1 =(按钮)findViewById(R.id.button1);
     //注册UI元素的处理程序
        mButton1.setOnClickListener(新View.OnClickListener()
        {
            公共无效的onClick(视图v)
            {
                Log.d(TAGmButton1点击);
                。字符串关键字= mEditText1.getText()的toString();
                networkthread OB =新networkthread(关键字);
            }
        });
    }
}类networkthread实现Runnable
{
    公共静态最后的字符串标记=SearchRecord;
    字符串关键字;
    公共networkthread(字符串关键字)
    {
        this.keyword =关键字;
        线程t =新主题(本);
        t.start();
    }
    公共无效的run()
    {
        Log.v(TAG的子线程内);
        尝试
        {
            Log.v(TAG,内部试);
            Log.v(TAG,康涅狄格州之前);
            网址URL =新的URL(http://10.0.2.2:8080/My_project/yahoo);
            HttpURLConnection的康恩=(HttpURLConnection类)url.openConnection();
            conn.setDoInput(真);
            conn.setDoOutput(真);
            conn.setRequestMethod(POST);
            conn.setRequestProperty(内容类型,应用程序/ x-WWW的形式urlen codeD);
            conn.setRequestProperty(接受,应用程序/八位字节流);
            conn.connect();
            Log.v(TAG,康涅狄格州后);
            OutputStream的OUT = conn.getOutputStream();
            Log.v(TAGDOS之前);
            DataOutputStream类DOS =新的DataOutputStream类(出);
            Log.v(TAG,经过DOS);
            dos.writeInt(keyword.getBytes()的长度。);
            dos.write(keyword.getBytes(),0,keyword.getBytes()的长度。);
            dos.flush();
            dos.close();
            InputStream为= conn.getInputStream();
            DataInputStream以解散=新DataInputStream所(是);
            字符串状态= dis.readLine();
            康恩= NULL;
            Log.v(TAG,完成试);
        }
        赶上(例外五)
        {
            Log.v(TAG,异常:+ E);
            e.printStackTrace();
        }
    }
}

该Servlet是:

 进口java.io.IOException异常;
进口java.io.ObjectInputStream中;
进口的java.io.PrintWriter;
进口javax.servlet.ServletException;
导入的javax.servlet。*;
进口java.net *。
进口javax.servlet.http.HttpServlet;
进口javax.servlet.http.HttpServletRequest;
进口javax.servlet.http.HttpServletResponse;
导入java.nio中*。
进口java.io. *;公共类搜索延伸的HttpServlet {
    私人InputStream为= NULL;
    私人DataInputStream以DIS = NULL;
    PrintWriter的出来;
    保护无效服务(HttpServletRequest的请求,HttpServletResponse的响应)抛出了ServletException,IOException异常{
        尝试{
            OUT = response.getWriter();
            是= request.getInputStream();
            DIS =新DataInputStream所(是);
            INT LEN = dis.readInt();
            字节的数据[] =新的字节[LEN]
            dis.read(数据,0,LEN);
            字符串关键字=新的String(数据);
            的out.print(关键词:+关键字);
            is.close();
            透露();
            字符串s =成功;        }赶上(例外五)
        {
            的out.print(E);
        }
    }
    保护无效的doGet(HttpServletRequest的请求,HttpServletResponse的响应)
            抛出了ServletException,IOException异常{
        服务(请求,响应);
    }
}


解决方案

在问题肯定是在您的文章中Content-Type头。你告诉您要发送一个URL连接codeD格式,然后继续把原始字节数据在请求体中的servlet。

此外,你真的不需要写在体内的含量的长度 - 为什么不把它写在Content-Length头呢?为什么不更好地利用什么是建立在HTTP协议?

I am trying to make an application which has connection with the servlet. The debugger doesn't show any error and neither the servlet has any error but still code is not working This is the android application My_appActivity.java

package com.m_app.first_app;

import java.io.DataInputStream; 
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import com.m_app.first_app.R;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class My_appActivity extends Activity{
    public static final String TAG = "SearchRecord";
    private EditText mEditText1;
    private Button mButton1;

    @Override
    public void onCreate(Bundle icicle) 
    {
        Log.v(TAG, "Activity State: onCreate()");
        super.onCreate(icicle);
        setContentView(R.layout.main);

     // Obtain handles to UI objects
        mEditText1 = (EditText) findViewById(R.id.editText1);
        mButton1 = (Button) findViewById(R.id.button1);


     // Register handler for UI elements
        mButton1.setOnClickListener(new View.OnClickListener() 
        {
            public void onClick(View v) 
            {
                Log.d(TAG, "mButton1 clicked");
                String keyword = mEditText1.getText().toString();
                networkthread ob = new networkthread(keyword);
            }           
        });    
    }
}

class networkthread implements Runnable
{
    public static final String TAG = "SearchRecord";
    String keyword;
    public networkthread(String keyword)
    {
        this.keyword=keyword;
        Thread t = new Thread(this);
        t.start();
    }
    public void run()
    {
        Log.v(TAG,"Inside the sub thread"); 
        try 
        {
            Log.v(TAG,"Inside try");
            Log.v(TAG,"Before conn");
            URL url = new URL("http://10.0.2.2:8080/My_project/yahoo");
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();           
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            conn.setRequestProperty("Accept", "application/octet-stream");
            conn.connect();
            Log.v(TAG,"After conn");
            OutputStream out = conn.getOutputStream();
            Log.v(TAG,"Before DOS");
            DataOutputStream dos = new DataOutputStream(out);
            Log.v(TAG,"After DOS");
            dos.writeInt(keyword.getBytes().length);
            dos.write(keyword.getBytes(),0,keyword.getBytes().length);
            dos.flush();
            dos.close();
            InputStream is = conn.getInputStream();
            DataInputStream dis = new DataInputStream(is);
            String status = dis.readLine();
            conn = null;
            Log.v(TAG,"Finish try");
        } 
        catch (Exception e)
        {
            Log.v(TAG,"Exception: "+e);
            e.printStackTrace();
        }   
    }  
}

The Servlet is :

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.*;
import java.net.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.*;
import java.io.*;

public class search extends HttpServlet {
    private InputStream is = null;
    private DataInputStream dis = null;
    PrintWriter out;
    protected void service(HttpServletRequest request, HttpServletResponse response)throws ServletException , IOException{
        try{
            out=response.getWriter();
            is = request.getInputStream();
            dis = new DataInputStream(is);
            int len = dis.readInt();
            byte data[] = new byte[len];
            dis.read(data,0,len);
            String Keyword = new String(data);
            out.print("Keyword :"+Keyword);
            is.close();
            dis.close();
            String s= "success";

        } catch(Exception e)
        {
            out.print(e);
        }
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        service(request,response);
    }       
}

解决方案

Once problem is certainly the Content-Type header in your POST. You are telling the servlet that you are sending a URL encoded form and then proceed to put raw byte data in the request body.

Also, you really don't need to write the length of the content in the body - why not write it in the Content-Length header instead? Why not better utilise what is built in to the HTTP protocol?

这篇关于如何连接到从Android应用程序的servlet?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆