2

我正在创建一个连接到 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 之类的服务以与服务器交互需要什么

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

4

2 回答 2

7

这将帮助您:

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 证书。

于 2013-03-07T12:47:51.800 回答
3

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

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

3你可以设置信任Android端的每个人......不是那么安全......

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

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

我希望它有帮助!

于 2013-03-07T12:34:40.097 回答