带参数的URLConnection

时间:2016-01-30 11:52:25

标签: android httpurlconnection urlconnection

在我使用Apache库(org.apach.httpclient)向参数(BasicNameValuePair)的Php脚本发出请求之前,

然后现在我想删除那些库以减少APK尺寸和放大还因为它已弃用,

我尝试过很多解决方案&许多例子&没有一个人工作过,

这是我实际使用的代码(没有任何反应):

Cursor cursor = mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_TITLE, KEY_BODY, KEY_CATEGORY}, KEY_CATEGORY + "=?", new String[]{category}, null, null, KEY_CATEGORY);
ArrayList elements = new ArrayList();
while(cursor.moveToNext()) {
    elements.add(cursor.getString(cursor.getColumnIndex(KEY_TITLE)));
}
cursor.close();
// use elements variable,
// here you'll get ["A", "C"]
SimpleCursorAdapter notes =
        new SimpleCursorAdapter(this, R.layout.notes_row, elements, from, to);
mList.setAdapter(notes);

调用sendRequest():

public JSONObject sendRequest(final String link, final HashMap<String, String> values) {
    JSONObject object = null;
    Thread thread = new Thread() {
        @Override
        public void run() {

    HttpURLConnection conn;
    final int CONNECTION_TIMEOUT = 15 * 1000;
            Log.e("Tag", "Start");
    try {
        URL url = new URL(link);
        conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(CONNECTION_TIMEOUT);
        conn.setConnectTimeout(CONNECTION_TIMEOUT);
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.connect();
        Log.e("Tag", "Connect");
        if (values != null) {
            OutputStream os = conn.getOutputStream();
            OutputStreamWriter osWriter = new OutputStreamWriter(os, "UTF-8");
            BufferedWriter writer = new BufferedWriter(osWriter);
            Log.e("Tag", "Write " + values);
            writer.write(getPostData(values));

            writer.flush();
            writer.close();
            os.close();
        }

    }
    catch (MalformedURLException e) {}
    catch (IOException e) {}

        }

};
thread.start();
    return object;
}

Php脚本应该简单地在文件中写入值,但什么都不会发生(它与Apache HttpPost一起使用),

任何解决方案?

由于

1 个答案:

答案 0 :(得分:1)

我已使用此解决了我的问题:

           String data = "";
           try{
                data = URLEncoder.encode("Test01", "UTF-8") + "=" + URLEncoder.encode("value1", "UTF-8");
                data += "&" + URLEncoder.encode("Test02", "UTF-8") + "=" + URLEncoder.encode("value2", "UTF-8");
            }
           catch(UnsupportedEncodingException e){
           e.printStackTrace();
           }

而不是HashMap字符串,

我还关注了Android Developer Doc关于兼容性的推荐:

        if (Integer.parseInt(Build.VERSION.SDK) < Build.VERSION_CODES.FROYO) {
        System.setProperty("http.keepAlive", "false");
      }

调试时获取响应代码也很重要(我的是200 OK):

int responseCode=conn.getResponseCode();
Log.e("Tag", "Response Code " + String.valueOf(responseCode));

感谢@ELITE为您提供帮助&amp;关于使用$ _POST而不是$ _REQUEST,

的建议

由于