使用HttpPost的Android-Django通信

时间:2015-02-04 10:22:26

标签: android mysql json django

我正在尝试将数据存储到Django服务器中的数据库表(MySQL)中。我尝试使用" Postman - REST Client"谷歌Chrome插件和详细信息已成功写入表中。 (邮差链接: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:FATAL EXCEPTION:main     处理:product.httpcommu.app,PID:1159     显示java.lang.NullPointerException             at 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)             at 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(本地方法)

1 个答案:

答案 0 :(得分:0)

乍一看,我想,

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