java - 使用 HttpClient 发布 JSONObject 时出错

标签 java android httpclient json

我得到的错误是“StrictMode$AndroidBlockGuardPolicy.onNetwork”,使用

我在这里尝试做的是使用 jsonobject 将所有这些数据发布到服务器。我真的不知道在这里要做什么,因为我正在使用一个 Activity 和这个类来管理所有 http 请求。

这是我的代码:

import android.util.Log;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import java.io.IOException;  

public class HttpRequestManager {

String TAG = "Request Manager";

public String RegisterUser (String deviceId, String userNames, String userSurnames, String password,
                            String retypedPassword, String userIds,
                            String userCellphone, String userEmail) {



    //Log.i(TAG, deviceId);

    JSONObject registerFormObject = new JSONObject();

    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost("http://192.168.1.110:8000/api/v1/registration");

    try {

        try {

            registerFormObject.put("device_id", deviceId);
            registerFormObject.put("device_type", "a");
            registerFormObject.put("names", userNames);
            registerFormObject.put("surnames", userSurnames);
            registerFormObject.put("cell", userCellphone);
            registerFormObject.put("email", userEmail);
            registerFormObject.put("password1", password);
            registerFormObject.put("password2", retypedPassword);
            registerFormObject.put("identification", userIds);

        }catch (Exception e){

        }

        httpPost.setEntity(new StringEntity(registerFormObject.toString()));
        //httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-type", "application/json");

        HttpResponse response = httpClient.execute(httpPost);

        Log.i(TAG, response.toString());

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        Log.i(TAG, e.toString());
    } catch (IOException e) {
        // TODO Auto-generated catch block
        Log.i(TAG, e.toString());
    }


    return userSurnames;
} 


}

知道如何解决此错误吗?

uses-permission android:name="android.permission.INTERNET"顺便说一句已完成。

最佳答案

@Machinarius 所说的是正确的。您无法在主线程上执行网络 Activity 。不过,为了回答您的问题,我为您提供了解决方案。

您可以创建一个新类...将其命名为您喜欢的任何名称(出于本示例的目的,我们假设它将是 RegUser)并在该类中...放置此代码。当然,更改参数注册功能将采用您的参数。

public void Register(
                          // Parameters it takes IN
                            String deviceId, 
                            String userNames, 
                            String userSurnames, 
                            String password,
                            String retypedPassword, 
                            String userIds,
                            String userCellphone, 
                            String userEmail
                          )
        {
        //Start of the Code in Function

        //Create a JSON variable of type JSON
        JSONObject JSON = new JSONObject();


        //Get UnixTimeStamp (Used to get UniquePushMessageID)
        long unixTime = System.currentTimeMillis() / 1000L;

        //Wrap all contacts and variabels to a single JSON object


    try {
                JSON.put("deviceId", deviceId);
                JSON.put("userNames", userNames);
                JSON.put("userSurnames", userSurnames);
                JSON.put("password", password);
...please add more yourself.
                JSON.put("contact", JSONcontacts); // Put JSON into JSON to create Array of Contacts
                JSON.put("channel", channel);
                JSON.put("unique", channel + String.valueOf(unixTime) ); //Create Unique MessageID (RSU-MAC+TimeInSec)
                JSON.put("icon", icon);

            } catch (JSONException e) {
                e.printStackTrace();

            }

            Log.v("MAD", "About to send" + JSON.toString());

            //Send this JSON object to a server
            SendToServer(JSON.toString());
}

现在,在同一个类中,请创建一个名为 SendToServer 的方法。正如您所看到的,它使用异步任务:)

@SuppressWarnings({ "unchecked", "rawtypes" })
    public void SendToServer(final String JSON) {
        new AsyncTask() {

            @SuppressWarnings("unused")
            protected void onPostExecute(String msg) {
                //Not Needed
            }

            protected Object doInBackground(Object... params) {
                //Create Array of Post Variabels
                ArrayList<NameValuePair> postVars = new ArrayList<NameValuePair>();

                //Add a 1st Post Value called JSON with String value of JSON inside
                //This is first and last post value sent because server side will decode the JSON and get other vars from it.
                postVars.add(new BasicNameValuePair("JSON", String.valueOf(JSON)));

                //Declare and Initialize Http Clients and Http Posts
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(YOUR_URL);

                //Format it to be sent
                try {
                    httppost.setEntity(new UrlEncodedFormEntity(postVars));

                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }

                /* Send request and Get the Response Back */
                try {
                    HttpResponse response = httpclient.execute(httppost);
                    String responseBody = EntityUtils.toString(response.getEntity());
                    //Log.v("MAD", "RESPONSE: " + responseBody + " | Length: " + String.valueOf(responseBody.length()));

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


                return null;
            }
        }.execute(null, null, null);

    }// END of Send to Server

就是这样。现在,在您的 MainActivity 中,您所要做的就是声明 RegUser:

RegUser registerUser = new RegUser();

在您输入数据的所有 TextFields 之后...只需一个简单的调用:

registerUser.Register(username, password.. etc);

我希望这能解决您的问题,它对我有用。

关于java - 使用 HttpClient 发布 JSONObject 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24899609/

相关文章:

java - 创建 bean 时出错

java - 如何获得正确的编码?

java - 如何在android中获取json值

android 在 View 下方添加阴影

Java - 为什么 HttpClient 不发送我的 cookie?

android - 如何将 CookieManager 持有的 cookie 传递给 Android 中的 Jsoup?

java - 通过循环更改矩阵的名称

java - 部署到 tomcat 5.5 时,我的 grails 项目中的 jar 没有被拾取

android - 无法从数据库中检索列的数据

android - HTTP 响应 411 长度要求,Http 客户端 4.0.1 Android