使用 HttpPost 进行 Android-Django 通信

标签 android mysql json django

我正在尝试将数据存储到 Django 服务器中的数据库表(MySQL)中。我尝试使用“Postman - REST Client”google chrome 插件,详细信息已成功写入表中。 ( postman 链接:https://chrome.google.com/webstore/detail/postman-rest-client/fdmmgilgnpjigdojojpjoooidkmcomcm?hl=en)。 但是当我尝试从 Android 进行通信时,我无法成功。请帮帮我。

代码:MainActivity.java

`private static final String TAG = "MainActivity";
private static final String URL = "http://172.21.1.59:4444/polls/";
JSONObject jsonObjSend;
product.httpcommu.app.HttpClient obj = new product.httpcommu.app.HttpClient();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button send = (Button) findViewById(R.id.btnsend);
    jsonObjSend = new JSONObject();
    try {
        // Add key/value pairs
        jsonObjSend.put("username", "root");
        jsonObjSend.put("password", "root");

        // Add a nested JSONObject (e.g. for header information)
        JSONObject header = new JSONObject();
        header.put("deviceType","Android"); // Device type
        header.put("deviceVersion","2.0"); // Device OS version
        header.put("language", "es-es");    // Language of the Android client
        jsonObjSend.put("header", header);

        // Output the JSON object we're sending to Logcat:
        Log.i(TAG, jsonObjSend.toString(2));

    } catch (JSONException e) {
        Log.e(TAG, ""+e);
        e.printStackTrace();
    }

    send.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            // Send the HttpPostRequest and receive a JSONObject in return

            JSONObject jsonObjRecv = obj.SendHttpPost(URL, jsonObjSend);
            Log.i(TAG,jsonObjRecv.toString());
        }
    });`

代码:HttpClient.java

`private static final String TAG = "HttpClient";
public static JSONObject SendHttpPost(String URL, JSONObject jsonObjSend) {

    try {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpPost httpPostRequest = new HttpPost(URL);

        StringEntity se;
        se = new StringEntity(jsonObjSend.toString());

        // Set HTTP parameters
        httpPostRequest.setEntity(se);
        httpPostRequest.setHeader("Accept", "application/json");
        httpPostRequest.setHeader("Content-type", "application/json");
        httpPostRequest.setHeader("Accept-Encoding", "gzip"); // only set this parameter if you would like to use gzip compression

        long t = System.currentTimeMillis();
        HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
        Log.i(TAG, "HTTPResponse received in [" + (System.currentTimeMillis()-t) + "ms]");

        // Get hold of the response entity (-> the data):
        HttpEntity entity = response.getEntity();

        if (entity != null) {
            // Read the content stream
            InputStream instream = entity.getContent();
            Header contentEncoding = response.getFirstHeader("Content-Encoding");
            if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
                instream = new GZIPInputStream(instream);
            }

            // convert content stream to a String
            String resultString= convertStreamToString(instream);
            instream.close();
            resultString = resultString.substring(1,resultString.length()-1); // remove wrapping "[" and "]"

            // Transform the String into a JSONObject
            JSONObject jsonObjRecv = new JSONObject(resultString);
            // Raw DEBUG output of our received JSON object:
            Log.i(TAG,"<JSONObject>\n"+jsonObjRecv.toString()+"\n</JSONObject>");

            return jsonObjRecv;
        } 

    }
    catch (Exception e)
    {
        // More about HTTP exception handling in another tutorial.
        // For now we just print the stack trace.
        e.printStackTrace();
    }
    return null;
}


private static String convertStreamToString(InputStream is) {
    /*
     * To convert the InputStream to String we use the BufferedReader.readLine()
     * method. We iterate until the BufferedReader return null which means
     * there's no more data to read. Each line will appended to a StringBuilder
     * and returned as String.
     * 
     * (c) public domain: http://senior.ceng.metu.edu.tr/2009/praeda/2009/01/11/a-simple-restful-client-at-android/
     */
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}`

代码:activity_main.xml

`<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context="product.httpcommu.app.MainActivity">

<TextView
    android:text="@string/hello_world"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Send Json"
    android:id="@+id/btnsend"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true" />

</RelativeLayout>`

错误日志: 02-06 00:36:46.800 1159-1159/product.httpcommu.app E/AndroidRuntime:致命异常:main 进程:product.httpcommu.app,PID:1159 java.lang.NullPointerException 在product.httpcommu.app.MainActivity$1.onClick(MainActivity.java:53) 在 android.view.View.performClick(View.java:4438) 在 android.view.View$PerformClick.run(View.java:18422) 在 android.os.Handler.handleCallback(Handler.java:733) 在 android.os.Handler.dispatchMessage(Handler.java:95) 在 android.os.Looper.loop(Looper.java:136) 在 android.app.ActivityThread.main(ActivityThread.java:5017) 在 java.lang.reflect.Method.invokeNative( native 方法) 在 java.lang.reflect.Method.invoke(Method.java:515) 在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 在dalvik.system.NativeStart.main( native 方法)

最佳答案

乍一看,我认为,

在 MainActivity.java 文件中,您将在按钮的单击事件中发送 Http 请求。相反,创建一个线程,然后尝试与您的服务器进行通信。当您通过 UI 线程执行此操作时,它会被阻塞并且应用程序会引发异常。只需尝试使用另一个线程即可。声明一个线程并在其 run() 方法中发送请求。我想这应该可以解决问题。

关于使用 HttpPost 进行 Android-Django 通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28318895/

相关文章:

android - 使用存储访问框架打开特定目录

android - 使用 ACTION_SEND 或 ACTION_SEND_MULTIPLE 发送图像和文本

java - JPA IdClass 混淆 - 这个想法实用吗?

javascript - IE8 中未声明 JSON 错误

java - 如何从 Rss 获取图片

Android - 重绘 Canvas

mysql - Django 存储数百万产品价格历史的最佳方式?

php - 更新购物车数量而不更新其他产品

javascript - 使用 json_encode() 将 php 数组转为 javascript

javascript - 在javascript中从json数组动态生成表