无法从Android连接到Servlet

时间:2012-07-31 08:20:46

标签: java android servlets

这是我的java代码:

 @SuppressLint({ "ParserError", "ParserError" })
  public class MainActivity extends Activity {

 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
      InputStream is=null;
String result = "";
TextView tv=(TextView)findViewById(R.id.tv);
//the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("name","shrey"));

//http post
 try{
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://10.0.2.2:8081/onlinechat");
      httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
       is = entity.getContent();

 }
 catch (ClientProtocolException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
//convert response to string
try{
    BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
        }
        is.close();

        result=sb.toString();
        tv.setText(result);

}catch(Exception e){
        Log.e("log_tag", "Error converting result "+e.toString());
}

//parse json data
   /*   try{
          JSONArray jArray = new JSONArray(result);
        for(int i=0;i<jArray.length();i++){
                JSONObject json_data = jArray.getJSONObject(i);
                Log.i("log_tag" , "name: "+json_data.getString("user")


                );
        }

}
 catch (JSONException e)
 {
        Log.e("log_tag", "Error parsing data "+e.toString());
   }
*/

 }


 }

这是我的Servlet代码:

  public class android extends HttpServlet {

/**
 * Processes requests for both HTTP
 * <code>GET</code> and
 * <code>POST</code> methods.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
 protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
   String user=request.getParameter("name").toString();
 /* BufferedReader reader = new BufferedReader( new  InputStreamReader(request.getInputStream() ) );  
                  String res = reader.readLine();  
     while( null != res )  
                   {  
                                         System.out.println( res );  
                            res = reader.readLine();  
                    }  

                  /*InputStream is = new        BufferedInputStream(request.getInputStream());      
        byte[] buf = new byte[8096]; 
            int bytesRead; 
            System.out.println("readbuf "+ is.read( buf )); 
                                while( ( bytesRead = is.read( buf ) ) != -1 )  
                os.write( buf, 0, bytesRead );  */  



    out.print("welcome"+user);
    out.println("success");




 }

  // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
 * Handles the HTTP
 * <code>GET</code> method.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
  @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
      processRequest(request, response);
     }

/**
 * Handles the HTTP
 * <code>POST</code> method.
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
   @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
     processRequest(request, response);
   }

/**
 * Returns a short description of the servlet.
 *
 * @return a String containing servlet description
 */
   @Override
  public String getServletInfo() {
      return "Short description";
   }// </editor-fold>
    }

我已在我的清单中添加了互联网权限,但仍然无法运行。这是调试器结束后我的logcat

07-31 13:45:50.874: E/log_tag(666): Error converting result java.lang.NullPointerException

2 个答案:

答案 0 :(得分:0)

您还没有完成setcontentView。所以我认为tv.setText(结果)中的tv为null; 在Oncreate中执行setcontentView

答案 1 :(得分:0)

我认为您的网址只能在本地子网中使用,而不是来自全球。检查一次。