且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

机器人发送HTTP POST请求发送到服务器

更新时间:2023-02-26 13:40:40

这将帮助你:

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;

}
 }

您可以使用上面的类是这样的: 例如:

You can use the above class like this: eg:

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();
 }
 }


如何使用它:
只是通过复制有关类code创建新JSONParse类。 然后你就可以如图二code(自第二code)在你的应用中调用它的任何。
你需要给清单的权限:


How to use it:
Just create new JSONParse class by copying about class code. Then you can call it any where in your application as shown in second code(Customize the second code).
You need to give manifest permission:

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

没有必要检查SSL证书。

No need to check SSL certificate.