你如何从servlet中的HttpResponse获取内容?

时间:2014-07-16 06:56:53

标签: java android servlets mobile

我目前正在学习开发Android应用程序。我需要解析从我的android应用程序到servlet的变量。我使用HttpResponse来解析变量。但我不知道如何接受servlet中的参数。

这是我在Android应用程序中的代码。

// Create a new HttpClient and Post Header
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://<ip_address>:8080/GetPhoneNumber/GetPhoneNumberServletServlet");

            try {
                // Add your data
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                nameValuePairs.add(new BasicNameValuePair("phoneNum", "12345678"));
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                // Execute HTTP Post Request
                HttpResponse response = httpclient.execute(httppost);

            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        } // End of onClick method

我可以在servlet中知道如何处理doPost / doGet吗?

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
    PrintWriter out = response.getWriter();
    out.println("Hello Android !!!!");
}

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
}

2 个答案:

答案 0 :(得分:1)

doPost使用request.getParameter("phoneNum")

答案 1 :(得分:1)

我认为以下代码可以帮助您。

public class CustomHttpClient 
{
 public static final int HTTP_TIMEOUT = 30 * 1000;
 private static HttpClient mHttpClient;
 private static HttpClient getHttpClient()
 {
  if (mHttpClient == null) 
    {
    mHttpClient = new DefaultHttpClient();
    final HttpParams params = mHttpClient.getParams();
    HttpConnectionParams.setConnectionTimeout(params, HTTP_TIMEOUT);
    HttpConnectionParams.setSoTimeout(params, HTTP_TIMEOUT);
    ConnManagerParams.setTimeout(params, HTTP_TIMEOUT);
    }
  return mHttpClient;
 }
 public static String executeHttpPost(String url,ArrayList<NameValuePair> postParameters) throws Exception 
   {
     BufferedReader in = null;
     try
     {
         HttpClient client = getHttpClient();
         HttpPost request = new HttpPost(url);
         UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
         request.setEntity(formEntity);
         HttpResponse response = client.execute(request);
         in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
         StringBuffer sb = new StringBuffer("");
         String line = "";
         String NL = System.getProperty("line.separator");
         while ((line = in.readLine()) != null) {
         sb.append(line + NL);   
     }
     in.close();
     String result = sb.toString();
     return result;
  } 
  finally 
  {
   if (in != null)
    {
    try 
        {
        in.close();
        }
    catch (IOException e)
        {
        Log.e("log_tag", "Error converting result "+e.toString()); 
        e.printStackTrace();
        }
    }
  }
 }
 public static String executeHttpGet(String url) throws Exception 
    {
        BufferedReader in = null;
        try
            {
                HttpClient client = getHttpClient();
                HttpGet request = new HttpGet();
                request.setURI(new URI(url));
                HttpResponse response = client.execute(request);
                in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
                StringBuffer sb = new StringBuffer("");
                String line = "";
                String NL = System.getProperty("line.separator");
                while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
     in.close();
     String result = sb.toString();
     return result;
    }
finally
    {
        if (in != null)
            {
                try
                    {
                        in.close();
                    }
                catch (IOException e)
                    {
                        Log.e("log_tag", "Error converting result "+e.toString()); 
                        e.printStackTrace();
                    }
            }
    }
  }
}

扩展中心: -

使用下面的JSON Parser类: -

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method,
            List<NameValuePair> params) {

        // Making HTTP request
        try {

            // check for request method
            if(method == "POST"){
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            }else if(method == "GET"){
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }           


        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        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();
            json = sb.toString();
            Log.d("json data",json.toString());
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

现在,如果您想在服务器上发送任何内容,请说您需要使用JSON Parser在服务器上保存用户名和密码,PHP在任何线程或Async任务的doInBackground方法中使用以下代码。

ArrayList<NameValuePair> Insert = new ArrayList<NameValuePair>();
                    Insert.add(new BasicNameValuePair("User_Name","<Sting denoting username>"));
                    Insert.add(new BasicNameValuePair("Password","<Sting denoting Password>));

                    try
                    {
                        HttpClient httpclient = new DefaultHttpClient();
                        HttpPost httppost = new HttpPost("http://server path/yourphpfile.php");
                        httppost.setEntity(new UrlEncodedFormEntity(Insert));
                        HttpResponse response = httpclient.execute(httppost);
                        HttpEntity entity = response.getEntity();
                        is = entity.getContent();
                    }   
                    catch(Exception e)
                    {
                        Log.e("log_tag", "Error in http connection"+e.toString());
                    }

现在,如果您需要使用JSON Parser中的get方法返回这些值,请在Async任务的Thread或doInBackground方法中再次使用以下代码。

public class CountDownTask extends AsyncTask<Void,Void , Void>
    {
        protected void onPreExecute() 
        {
            count = 0;
            S_Store_Id = null; S_Store_Name = null;S_Store_Address = null; S_Store_Phone= null;
            Offers = null; Descriptions = null;
        }
        protected Void doInBackground(Void... params)
        {   

            ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
            postParameters.add(new BasicNameValuePair("User_Name",StringUserName));
            String response = null;
            try 
            {
                response = CustomHttpClient.executeHttpPost("http://yourserverpath/yourphpfilefor retrivingdata.php",postParameters);
                String result = response.toString();
                try
                {
                    JSONArray jArray = new JSONArray(result);

                    JSONObject json_data = jArray.getJSONObject(0);

                    StringUserName = json_data.getString("User_Name");
                    StringPassword = json_data.getString("Password");

                    json_data = jArray.getJSONObject(1);
                    }
                catch(JSONException e)
                {
                    Log.e("log_tag", "Error parsing data "+e.toString());
                }
            }
            catch (Exception e)
            {
                Log.e("log_tag","Error in http connection!!" + e.toString());     
            }
            return null;
        }

现在,您可以在相应的PHP文件中编写用于从服务器插入和检索数据的逻辑,并使用它们来使用服务器中的数据。此方法与HTTP请求和响应的HTTP Get和Post方法等效。

希望它可以帮助你......谢谢......