Android向服务器发送HTTP POST请求

时间:2013-03-07 12:21:15

标签: android web-services interface httpclient

我正在创建一个连接到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等服务与服务器交互的需求是什么?

  6. 我在这个领域更新鲜..请给我答案我的怀疑.. 请支持我......

2 个答案:

答案 0 :(得分: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证书。

答案 1 :(得分:3)

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

2 URLConnection,但在Android上更好地使用AsyncTask,特别是对于Android +4

3你可以设置为信任Android方面的所有人......不那么安全..

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

5有两种方法可以手动或自动执行libraryesmarshaling,unmarshaling。 JSON的开销较小。

我希望它有所帮助!