【问题标题】:Android sending HTTP POST request to the serverAndroid 向服务器发送 HTTP POST 请求
【发布时间】:2013-03-07 12:21:14
【问题描述】:

我正在创建一个连接到 cakePHP 网站的应用程序 我创建了一个默认的 HTTP 客户端并向服务器发送一个 HTTP POST 请求。 数据以 json 格式来自服务器,在客户端我从 json 数组中获取值,这是我的项目结构。 下面我展示了一些我用来连接服务器的代码

        try{
             HttpClient httpclient = new DefaultHttpClient();
             HttpPost httppost = new HttpPost("http://10.0.2.2/XXXX/logins/login1");

        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8));
        response = httpclient.execute(httppost);
        StringBuilder builder = new StringBuilder();
               BufferedReader   reader = new BufferedReader

            (new     InputStreamReader(response.getEntity().getContent(), "UTF-8"));

              for (String line = null; (line = reader.readLine()) != null;) 

                    {
                    builder.append(line).append("\n");
                    }

              JSONTokener   tokener = new JSONTokener(builder.toString());
              JSONArray  finalResult = new JSONArray(tokener);
              System.out.println("finalresulttttttt"+finalResult.toString());
              System.out.println("finalresul length"+finalResult.length());
                Object type = new Object();

              if (finalResult.length() == 0 && type.equals("both")) 
            {
        System.out.println("null value in the json array");


                }
    else {

           JSONObject   json_data = new JSONObject();

            for (int i = 0; i < finalResult.length(); i++) 
               {
                   json_data = finalResult.getJSONObject(i);

                   JSONObject menuObject = json_data.getJSONObject("Userprofile");

                   group_id= menuObject.getString("group_id");
                   id = menuObject.getString("id");
                   name = menuObject.getString("name");
                }
                    }
                        }


                  catch (Exception e) {
               Toast.makeText(FirstMain.this,"exceptionnnnn",Toast.LENGTH_LONG).show();
                 e.printStackTrace();
                    }

我的问题是

  1. 我需要将每个页面都连接到服务器,因为我需要在所有活动中每次都编写代码,有没有其他方法可以连接到服务器并从每个活动发送请求?接口的概念类似于......
  2. android 库是否提供任何用于连接服务器的类?
  3. 是否需要检查所有验证,例如客户端的 SSL 证书?

  4. 从 android 连接到服务器是否需要任何其他要求?

  5. 实现 SOAP REST 等服务以与服务器交互需要什么

我是这个领域的新手..请回答我的疑问.. 请支持我...

【问题讨论】:

    标签: android web-services interface httpclient


    【解决方案1】:

    这将对您有所帮助:

    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 method
    public JSONObject makeHttpRequest(String url, String method,
            List<NameValuePair> params) throws Exception {
    
        // 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));
    
                // new
                HttpParams httpParameters = httpPost.getParams();
                // Set the timeout in milliseconds until a connection is
                // established.
                int timeoutConnection = 10000;
                HttpConnectionParams.setConnectionTimeout(httpParameters,
                        timeoutConnection);
                // Set the default socket timeout (SO_TIMEOUT)
                // in milliseconds which is the timeout for waiting for data.
                int timeoutSocket = 10000;
                HttpConnectionParams
                        .setSoTimeout(httpParameters, timeoutSocket);
                // new
                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);
                // new
                HttpParams httpParameters = httpGet.getParams();
                // Set the timeout in milliseconds until a connection is
                // established.
                int timeoutConnection = 10000;
                HttpConnectionParams.setConnectionTimeout(httpParameters,
                        timeoutConnection);
                // Set the default socket timeout (SO_TIMEOUT)
                // in milliseconds which is the timeout for waiting for data.
                int timeoutSocket = 10000;
                HttpConnectionParams
                        .setSoTimeout(httpParameters, timeoutSocket);
                // new
                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }
    
        } catch (UnsupportedEncodingException e) {
            throw new Exception("Unsupported encoding error.");
        } catch (ClientProtocolException e) {
            throw new Exception("Client protocol error.");
        } catch (SocketTimeoutException e) {
            throw new Exception("Sorry, socket timeout.");
        } catch (ConnectTimeoutException e) {
            throw new Exception("Sorry, connection timeout.");
        } catch (IOException e) {
            throw new Exception("I/O error(May be server down).");
        }
        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();
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }
    
        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            throw new Exception(e.getMessage());
        }
    
        // return JSON String
        return jObj;
    
    }
     }
    

    你可以像这样使用上面的类: 例如:

    public class GetName extends AsyncTask<String, String, String> {
    String imei = "abc";
    JSONParser jsonParser = new JSONParser();
    
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }
    
    protected String doInBackground(String... args) {
        String name = null;
        String URL = "http://192.168.2.5:8000/mobile/";
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("username", mUsername));
        params.add(new BasicNameValuePair("password", mPassword));
        JSONObject json;
        try {
            json = jsonParser.makeHttpRequest(URL, "POST", params);
            try {
                int success = json.getInt(Settings.SUCCESS);
                if (success == 1) {
                    name = json.getString("name");
                } else {
                    name = null;
                }
            } catch (JSONException e) {
                name = null;
            }
        } catch (Exception e1) {
        }
        return name;
    }
    
    protected void onPostExecute(String name) {
        Toast.makeText(mcontext, name, Toast.LENGTH_SHORT).show();
     }
     }
    


    使用方法:
    只需通过复制类代码来创建新的 JSONParse 类。 然后您可以在应用程序中的任何位置调用它,如第二个代码所示(自定义第二个代码)。
    您需要授予清单权限:

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

    无需检查 SSL 证书。

    【讨论】:

    • 嗨 Vishal,我还有一个疑问,希望你能解决这个问题。在我的程序中,我有一个扩展 Activity 类的主类,我需要编写 - public class GetName extends AsyncTask - 这个类(你被提供)在一些 onclick 函数中。如何调用这个类??只有当有人单击按钮时我才需要执行此操作,这就是我在 onclick 函数中编写的原因
    • 嗨....当我使用 AsyncTask 扩展我的课程时 - 它显示错误。 AndroidRuntime(463):未捕获的处理程序:线程主因未捕获的异常而退出 E/AndroidRuntime(463):java.lang.RuntimeException:无法实例化活动 ComponentInfo{com.example.cakeconnect/com.example.cakeconnect.DeleteAllocatedRCard}:java .lang.ClassCastException: \com.example.cakeconnect.DeleteAllocatedRCard ,我需要扩展 Activity 类。怎么可能
    • 嗨 Vishal,你能理解我的问题吗?在每一项活动中,我都需要与服务器通信。我的问题是每个类都在扩展主要活动,那么如何扩展这个 -syncTask
    • 我很困惑..请给我一个解决方案
    • Dude..下载这个项目。把它作为你当前问题的参考https://github.com/vishalvijay/Fingerprint-Magic
    【解决方案2】:

    1 您可以编写一个实用程序类 HTTPPoster 并包装到 HTTPAsyncCall。在每个活动中使用该类并传递参数

    2 URLConnection,但在 Android 上最好使用 AsyncTask,尤其是对于 Android +4

    3 你可以在 Android 端设置信任每个人...不太安全..

    4 没有,但是在android manifest需要添加权限,比如internet

    5 有两种方法可以手动或自动使用 libraryesmarshaling、unmarshaling。 JSON 的开销更少。

    希望对你有帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-09-02
      • 1970-01-01
      • 2012-12-12
      • 1970-01-01
      • 1970-01-01
      • 2014-04-30
      • 1970-01-01
      相关资源
      最近更新 更多