Android 向服务器发送 HTTP POST 请求

标签 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. 我需要将每个页面与服务器连接起来,为此我需要在我的所有 Activity 中每次都编写代码,有没有其他方法可以连接到服务器并从每个 Activity 发送请求?接口(interface)的概念类似于……
  2. android 库是否提供任何用于连接到服务器的类?
  3. 是否需要在客户端检查SSL证书等所有验证?

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

  5. 实现SOAP REST等服务与服务器交互的需求是什么

我是这个领域的新人..请给我解答我的疑惑.. 请支持我...

最佳答案

这将帮助您:

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 类。 然后你可以在你的应用程序的任何地方调用它,如第二个代码所示(自定义第二个代码)。
您需要给予 list 许可:

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

无需检查SSL证书。

关于Android 向服务器发送 HTTP POST 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15271126/

相关文章:

php - 接口(interface)实现: declaration must be compatible

Tab 初始化的 Android 问题

java - Volley.NoConnectionError : java. io.EOFException 0

web-services - 每次网络服务调用时自动传递一个 cookie

c# - 如何在 WCF 中接受 BinarySecurityToken?

java - 通用 List 类型的 getter 和 setter 接口(interface)

安卓 : JNI ERROR (app bug): local reference table overflow (max=512)

android - 在 android 的 Horizo​​ntalscrollview 中一次显示一个布局

c# - WCF Restful返回HttpResponseMessage想在设置内容时进行协商

interface - 什么是空接口(interface)用于