【问题标题】:Android-Django communication using HttpPost使用 HttpPost 的 Android-Django 通信
【发布时间】:2015-04-03 19:52:52
【问题描述】:

我正在尝试将数据存储到 Django 服务器中的数据库表 (MySQL) 中。我尝试使用“Postman - REST Client”谷歌浏览器插件,详细信息已成功写入表中。 (邮递员链接: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: 致命例外:主要 进程: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 Method) 在 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 Method)

【问题讨论】:

  • when i tried to communicate from android, i could not make success 请说明您遇到了什么问题?
  • 哪一行给出了空指针异常?你能放完整/部分堆栈跟踪吗?
  • 请立即检查错误日志。

标签: android mysql json django


【解决方案1】:

我认为,一目了然,

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

【讨论】:

  • 谢谢帕里托什·沃尔维卡。当我尝试使用线程时它起作用了。但是应用程序在访问服务器后会关闭。正在努力。
  • 成功了。进行了以下更改:- public void run() { try { JSONObject jsonObjRecv = obj.SendHttpPost(URL, jsonObjSend); Log.i(TAG,jsonObjRecv.toString()); } 捕捉(异常 e){ e.printStackTrace(); } }
猜你喜欢
  • 1970-01-01
  • 2016-11-07
  • 2015-02-24
  • 1970-01-01
  • 2015-02-13
  • 2013-01-11
  • 2016-02-29
  • 2014-04-04
  • 1970-01-01
相关资源
最近更新 更多