从android向servlet发送GET请求时出错

时间:2014-04-09 10:05:25

标签: java android servlets

搜索后我能够从我的servlet中检索一个响应,但是我无法从android向servlet发送参数(用户名和密码参数)!我的logcat显示了这个错误:

04-0java.lang.ClassCastException: org.apache.http.client.methods.HttpGet cannot be cast to org.apache.http.HttpResponse
at com.example.httpgetandroidexample.MainActivity$AsyncTaskRunner.doInBackground(MainActivity.java:76)
at com.example.httpgetandroidexample.MainActivity$AsyncTaskRunner.doInBackground(MainActivity.java:1)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)

我不明白为什么! 这是我的主要活动:

package com.example.httpgetandroidexample;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {

               public TextView content;
                EditText name,pass;
                String URL,nameValue,passValue;
            @Override
            protected void onCreate(Bundle savedInstanceState) {

                      super.onCreate(savedInstanceState);
                     setContentView(R.layout.activity_main);

                     name      =  (EditText)findViewById(R.id.name);
                     pass       =  (EditText)findViewById(R.id.pass);
                     content       =  (TextView)findViewById(R.id.text);

                   Button button=(Button)findViewById(R.id.but);
                   try {
                    nameValue    =URLEncoder.encode(name.getText().toString(), "UTF-8");
                    passValue    =URLEncoder.encode(pass.getText().toString(), "UTF-8");
                       URL = "http://10.0.2.2:8080/login/web";
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }

                   button.setOnClickListener(new View.OnClickListener() {
                       @Override
                       public void onClick(View v) {
                        AsyncTaskRunner runner = new AsyncTaskRunner();
                        runner.execute(new String[ ] { URL });
                       }
                      });


   }
            private class AsyncTaskRunner extends AsyncTask<String, Void, String> {


                @Override
                protected String doInBackground(String... urls) {

                  String response = "";
                  for (String url : urls) {
                    DefaultHttpClient client = new DefaultHttpClient();
                    HttpGet httpGet = new HttpGet(url);
                    try {
                        List<NameValuePair> postParameters = 
                                new ArrayList<NameValuePair>();
                            postParameters.add(new BasicNameValuePair("user",nameValue));
                            postParameters.add(new BasicNameValuePair("pass",passValue));
                            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(
                                    postParameters);
                            ((HttpResponse) httpGet).setEntity(formEntity);
                      HttpResponse execute = client.execute(httpGet);
                      InputStream content = execute.getEntity().getContent();

                      BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
                      String s = "";
                      while ((s = buffer.readLine()) != null) {
                        response += s;
                      }

                    } catch (Exception e) {
                      e.printStackTrace();
                    }
                  }
                  return response;
                }

                @Override
                protected void onPostExecute(String result) {
                  content.setText(result);
                }
              }
}

有没有人有任何想法?

更新:

now i have changed my android code like this:
package com.example.httpgetandroidexample;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {

               public TextView content;
                EditText name,pass;
                String URL;
            @Override
            protected void onCreate(Bundle savedInstanceState) {

                      super.onCreate(savedInstanceState);
                     setContentView(R.layout.activity_main);

                     name      =  (EditText)findViewById(R.id.name);
                     pass       =  (EditText)findViewById(R.id.pass);
                     content       =  (TextView)findViewById(R.id.text);

                   Button button=(Button)findViewById(R.id.but);
                   try {
                    String nameValue    ="user="+URLEncoder.encode(name.getText().toString(), "UTF-8");
                    String passValue    ="&pass="+URLEncoder.encode(pass.getText().toString(), "UTF-8");
                       URL = "http://10.0.2.2:8080/login/web?"+nameValue+passValue;
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }

                   button.setOnClickListener(new View.OnClickListener() {
                       @Override
                       public void onClick(View v) {
                        AsyncTaskRunner runner = new AsyncTaskRunner();
                        runner.execute(new String[ ] { URL });
                       }
                      });


   }
            private class AsyncTaskRunner extends AsyncTask<String, Void, String> {


                @Override
                protected String doInBackground(String... urls) {

                  String response = "";
                  for (String url : urls) {
                    DefaultHttpClient client = new DefaultHttpClient();
                    HttpGet httpGet = new HttpGet(url);
                    try {

                      HttpResponse execute = client.execute(httpGet);
                      InputStream content = execute.getEntity().getContent();

                      BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
                      String s = "";
                      while ((s = buffer.readLine()) != null) {
                        response += s;
                      }

                    } catch (Exception e) {
                      e.printStackTrace();
                    }
                  }
                  return response;
                }

                @Override
                protected void onPostExecute(String result) {
                  content.setText(result);
                }
              }
}

这次运行没有logcat错误,但参数不会出现在servlet中!

2 个答案:

答案 0 :(得分:2)

查看堆栈跟踪,我猜你的问题就在这一行。

((HttpResponse) httpGet).setEntity(formEntity);

为什么要将它投射到HttpResponse

行。您想使用HTTP GET发送用户/传递参数。对于HTTP GET,所有参数都是URL的一部分。也许这可以为你提供一些如何执行HTTP GET和传递参数的帮助。但一般来说,URL看起来像这样

http://www.blah.com/servlet?user="1234"&pass="password"

URL中?之后的内容包含所有参数。但是URL中有一个长度限制,如果超过该长度,则必须使用HTTP POST。

尝试此链接,看看它是否可以帮到您 http://androidexample.com/How_To_Make_HTTP_Get_Request_To_Server_-_Android_Example/index.php?view=article_discription&aid=63&aaid=88

答案 1 :(得分:0)

我修改了活动,问题是在代码的错误部分声明了URLnameValue以及passValue!这是正确的android代码:

package com.example.httpgetandroidexample;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {

               public TextView content;
                EditText name,pass;
                String URL,nameValue,passValue;
            @Override
            protected void onCreate(Bundle savedInstanceState) {

                      super.onCreate(savedInstanceState);
                     setContentView(R.layout.activity_main);

                     name      =  (EditText)findViewById(R.id.name);
                     pass       =  (EditText)findViewById(R.id.pass);
                     content       =  (TextView)findViewById(R.id.text);
                     content.setText("Vendosni Perdoruesin dhe Fjalekalimin");
                   Button button=(Button)findViewById(R.id.but);



                   button.setOnClickListener(new View.OnClickListener() {
                       @Override
                       public void onClick(View v) {
                           nameValue="&user="+name.getText().toString();
                           passValue    ="&pass="+pass.getText().toString();
                           URL = "http://10.0.2.2:8080/login/web2?activitetiNR=1"+nameValue+passValue;
                        AsyncTaskRunner runner = new AsyncTaskRunner();

                           Log.i("url",URL);
                           Log.i("url",nameValue);
                           Log.i("url",passValue);
                        runner.execute(new String[ ] { URL });
                       }
                      });


   }
            private class AsyncTaskRunner extends AsyncTask<String, Void, String> {


                @Override
                protected String doInBackground(String... urls) {

                  String response = "";
                  for (String url : urls) {
                    DefaultHttpClient client = new DefaultHttpClient();
                    HttpGet httpGet = new HttpGet(url);
                    try {

                      HttpResponse execute = client.execute(httpGet);
                      InputStream content = execute.getEntity().getContent();

                      BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
                      String s = "";
                      while ((s = buffer.readLine()) != null) {
                        response += s;
                      }

                    } catch (Exception e) {
                      e.printStackTrace();
                    }
                  }
                  return response;
                }

                @Override
                protected void onPostExecute(String result) {
                  content.setText(result);
                }
              }
}