android - 如何在不使用Json的情况下在android中执行HTTP POST请求

标签 android mysql

我已经编写了这段代码,我将使用 POST 请求将数据发送到 MYSQL 数据库。我使用 POST 请求编写了以下代码。所以,只是想先问一下这段代码是否可以正常运行

如果有人能告诉我 setRequestProperty("Key","Value") 方法的具体用途以及其中的 KEY 和 VALUE 的含义,我将非常感激。

我也在 list 文件中提供了互联网权限。

请尽快回复。

try {
        URL url = new URL("http://192.168.221.105/hanish/datainsert.php");
        HttpURLConnection client = (HttpURLConnection) url.openConnection();


        client.setRequestMethod("POST");
        client.setRequestProperty(“id”,”l”);
        client.setDoOutput(true);

        OutputStream outputPost = new BufferedOutputStream(client.getOutputStream());
        writeStream(outputPost);

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

private void writeStream(OutputStream outputPost) throws IOException {
    String v= l;
    outputPost.write(v.getBytes());
    outputPost.flush();
} 

最佳答案

为此,您应该运行异步任务。但是,我建议使用 AsyncHttpClient图书馆。它为您处理异步请求。

要使用此库,您应该使用 Gradle 构建脚本添加 Maven 依赖项,格式为:

   dependencies {
     compile 'com.loopj.android:android-async-http:1.4.9'
   }

然后,导入http包:

import com.loopj.android.http.*;

然后编写如下代码:

AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
RequestParams requestParams = new RequestParams();
requestParams.add("id", "1");
asyncHttpClient.post("http://192.168.221.105/hanish/datainsert.php", requestParams, new AsyncHttpResponseHandler() {
    @Override
    public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
        String response = new String(responseBody); // this is your response string
    }

    @Override
    public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
        // Here you write code if there's error
    }
});

我希望这会有所帮助。

关于android - 如何在不使用Json的情况下在android中执行HTTP POST请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42883452/

相关文章:

java - 如果 “minimize” Android游戏崩溃

java - 如何在多个屏幕中处理 AssetManager

android - 将 actionbarsherlock 与 android-support-v4(版本 23)一起使用

java - Android:使用 HttpURLConnection 中的进度回调在 Cloudinary 中上传照片

php - JTable PHP 更新不起作用

php - 使用选中复选框中的选项从 mySQL 中检索结果

php - 如何在 Openshift 中打开数据库连接?

java - 如何修复搜索栏中的 ListView

mysql - 为什么mysql显示外键值两次

php - 获取最后插入的事件