BasicNetwork.performRequest:URL(POST)齐射

时间:2016-06-19 10:12:37

标签: android json web-services android-fragments android-volley

我正在开发一个Android应用程序,它将一个json object发送到一个api url,并且应该收到一个json对象作为response,但我一直得到这个error

BasicNetwork.performRequest: Unexpected response code 400 for http://phoneapi.adro.co/Services/AdService.svc/GetAd/

我正在使用volley

我的json objectrequest应该是这样的:

"request": {
"DeviceId": "sdasda" ,
"AppId": "ECC7BCE40126408386BCFCF8AB9187E7",
"AdType": "text",
"Location": "35.7209331,51.472983",
"UserOperator": "Irancell",
"Ip": "127.0.0.1",
"NetworkType": "3G",
"DeviceType": "Android",
"DeviceBrand": "Samsung",
"Width": 0,
"Height": 0,
"TestMode": true
}

这些是我的代码:

import android.app.DownloadManager;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class JsonObjectSend
{
    private static final String TAG_action = "Action";
    private static final String TAG_acValue = "ActionValue";
    private static final String TAG_bg = "BgColor";
    private static final String TAG_id = "CampId";
    private static final String TAG_ctype = "CampType";
    private static final String TAG_adr = "ClickAddress";
    private static final String TAG_endAnim = "EndAnimation";
    private static final String TAG_expText = "ExplainText";
    private static final String TAG_imType = "ImageType";
    private static final String TAG_imgUBanner = "ImageUrlBanner";
    private static final String TAG_imgULBanner = "ImageUrlLargBanner";
    private static final String TAG_imgUMRect = "ImageUrlMediumRectange";
    private static final String TAG_imgUFBanner = "ImageUrlFullBanner";
    private static final String TAG_imgULeadBrd = "ImageUrlLeaderBoard";
    private static final String TAG_logoU = "LogoUrl";
    private static final String TAG_mainText = "MainText";
    private static final String TAG_packName = "PackageName";
    private static final String TAG_repText = "ReplaceText";
    private static final String TAG_startAnim = "StartAnimation";
    private static final String TAG_videoU = "VideoUrl";
    private static final String TAG_type = "type";
    private static final String TAG_atag = "atag";
    private static final String TAG_msg = "message";
    private static final String TAG_pix = "pixel";
    private static final String TAG_scrpt = "script";
    private static final String TAG_tkn = "token";

    public void sendobj()
    {
        final JSONObject jsonBody = new JSONObject();
        try {
            jsonBody.put("DeviceId", "sdasda");
            jsonBody.put("AppId", "ECC7BCE40126408386BCFCF8AB9187E7");
            jsonBody.put("AdType", "text");
            jsonBody.put("Location", "35.7209331,51.472983");
            jsonBody.put("UserOperator", "Irancell");
            jsonBody.put("Ip", "127.0.0.1");
            jsonBody.put("NetworkType", "3G");
            jsonBody.put("DeviceType", "Android");
            jsonBody.put("DeviceBrand", "Samsung");
            jsonBody.put("Width", "0");
            jsonBody.put("Height", "0");
            jsonBody.put("TestMode", "true");


        }
        catch (JSONException e)
        {
            e.printStackTrace();
        }
        String tag_string_req = "Send_Object";
        Map<String, String> params = new HashMap<String, String>();
        params.put("Content-Type", "application/json; charset=utf-8");
        params.put("DeviceId", "sdasda");
        params.put("AppId", "ECC7BCE40126408386BCFCF8AB9187E7");
        params.put("AdType", "text");
        params.put("Location", "35.7209331,51.472983");
        params.put("UserOperator", "Irancell");
        params.put("Ip", "127.0.0.1");
        params.put("NetworkType", "3G");
        params.put("DeviceType", "Android");
        params.put("DeviceBrand", "Samsung");
        params.put("Width", "0");
        params.put("Height", "0");
        params.put("TestMode", "true");
        JsonObjectRequest Req = new JsonObjectRequest(Request.Method.POST, AppConfig.API_URL, new JSONObject(params), new Response.Listener<JSONObject>()
        {
            @Override
            public void onResponse(JSONObject response)
            {
                try
                {
                    JSONObject jObj = response;
                    boolean error = jObj.getBoolean("error");
                    if (!error)
                    {
                        String action = jObj.getString(TAG_action);
                        String actionvalue = jObj.getString(TAG_acValue);
                        String bg = jObj.getString(TAG_bg);
                        String campid = jObj.getString(TAG_id);
                        String camptype = jObj.getString(TAG_ctype);
                        String clickadr = jObj.getString(TAG_adr);
                        String endanim = jObj.getString(TAG_endAnim);
                        String exptext = jObj.getString(TAG_expText);
                        String imgtype = jObj.getString(TAG_imType);
                        String imgurlbanner = jObj.getString(TAG_imgUBanner);
                        String imgurllargebanner = jObj.getString(TAG_imgULBanner);
                        String imgurlmedrectangle = jObj.getString(TAG_imgUMRect);
                        String imgurlfullbanner = jObj.getString(TAG_imgUFBanner);
                        String imgurlleaderboard = jObj.getString(TAG_imgULeadBrd);
                        String logourl = jObj.getString(TAG_logoU);
                        String maintext = jObj.getString(TAG_mainText);
                        String packagename = jObj.getString(TAG_packName);
                        String replacetext = jObj.getString(TAG_repText);
                        String startenim = jObj.getString(TAG_startAnim);
                        String videourl = jObj.getString(TAG_videoU);
                        String type = jObj.getString(TAG_type);
                        String atag = jObj.getString(TAG_atag);
                        String msg = jObj.getString(TAG_msg);
                        String pixel = jObj.getString(TAG_pix);
                        String script = jObj.getString(TAG_scrpt);
                        String token = jObj.getString(TAG_tkn);
                        Log.d("action", action);
                    } else
                    {
                        String errorMsg = jObj.getString("error_msg");
                        Log.d("Debug", errorMsg);
                    }
                }
                catch (JSONException e)
                {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d("error", "Error");
                Log.i("onErrorResponse", error.toString());
            }
        });


        // Adding request to request queue
        AppController.getInstance().addToRequestQueue(Req, tag_string_req);
    }

}//class end

这是我的app控制器:

public class AppController extends Application
{

    public static final String TAG = AppController.class.getSimpleName();
    private RequestQueue mRequestQueue;
    private static AppController mInstance;

    @Override
    public void onCreate()
    {
        super.onCreate();
        mInstance = this;
    }

    public static synchronized AppController getInstance()
    {
        return mInstance;
    }

    public RequestQueue getRequestQueue()
    {
        if (mRequestQueue == null)
        {
            //  mRequestQueue = Volley.newRequestQueue(getApplicationContext());
            Network network = new BasicNetwork(new OkHttpStack());
            mRequestQueue = new RequestQueue(new DiskBasedCache(new File(getCacheDir(), "volley")), network);
            mRequestQueue.start();
        }

        return mRequestQueue;
    }

    public class OkHttpStack extends HurlStack
    {
        private final OkUrlFactory mFactory;
        public OkHttpStack()
        {
            this(new OkHttpClient());
        }

        private  OkHttpClient getUnsafeOkHttpClient()
        {
            try {
                final TrustManager[] trustAllCerts = new TrustManager[]
                        {
                                new X509TrustManager()
                                {
                                    @Override
                                    public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) {}

                                    @Override
                                    public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) {}

                                    @Override
                                    public java.security.cert.X509Certificate[] getAcceptedIssuers()
                                    {
                                        return null;
                                    }
                                }
                        };
                final SSLContext sslContext = SSLContext.getInstance("SSL");
                sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
                final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
                OkHttpClient okHttpClient = new OkHttpClient();
                okHttpClient.setSslSocketFactory(sslSocketFactory);
                okHttpClient.setHostnameVerifier(new HostnameVerifier()
                {
                    @Override
                    public boolean verify(String hostname, SSLSession session)
                    {
                        return true;
                    }
                });
                return okHttpClient;
            }
            catch (Exception e)
            {
                throw new RuntimeException(e);
            }
        }




        public OkHttpStack(OkHttpClient client)
        {
            client=getUnsafeOkHttpClient();
            if (client == null)
            {
                throw new NullPointerException("Client must not be null.");
            }
            mFactory = new OkUrlFactory(client);
        }

        @Override
        protected HttpURLConnection createConnection(URL url) throws IOException
        {
            return mFactory.open(url);
        }
    }


    public <T> void addToRequestQueue(Request<T> req, String tag)
    {
        req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
        getRequestQueue().add(req);
    }

    public <T> void addToRequestQueue(Request<T> req)
    {
        req.setTag(TAG);
        getRequestQueue().add(req);
    }

    public void cancelPendingRequests(Object tag)
    {
        if (mRequestQueue != null)
        {
            mRequestQueue.cancelAll(tag);
        }
    }
}

这是我的logcat:

 06-19 06:04:43.991  23858-23858/? D/﹕ HostConnection::get() New Host Connection established 0xb3ec8aa0, tid 23858
06-19 06:04:46.895  23858-23858/com.noxel.test W/chromium﹕ [WARNING:mailbox_synchronizer.cc(41)] MailboxSync not supported due to missing EGL image/fence support
06-19 06:04:46.903  23858-23858/com.noxel.test W/chromium﹕ [WARNING:data_reduction_proxy_settings.cc(331)] SPDY proxy OFF at startup
06-19 06:04:46.909  23858-23858/com.noxel.test W/art﹕ Attempt to remove local handle scope entry from IRT, ignoring
06-19 06:04:46.910  23858-23858/com.noxel.test W/AwContents﹕ onDetachedFromWindow called when already detached. Ignoring
06-19 06:04:46.918  23858-23907/com.noxel.test D/OpenGLRenderer﹕ Use EGL_SWAP_BEHAVIOR_PRESERVED: true
06-19 06:04:46.936  23858-23858/com.noxel.test D/Atlas﹕ Validating map...
06-19 06:04:46.989  23858-23907/com.noxel.test I/OpenGLRenderer﹕ Initialized EGL, version 1.4
06-19 06:04:46.990  23858-23907/com.noxel.test D/﹕ HostConnection::get() New Host Connection established 0xb3ff9be0, tid 23907
06-19 06:04:47.039  23858-23907/com.noxel.test D/OpenGLRenderer﹕ Enabling debug mode 0
06-19 06:04:47.126  23858-23907/com.noxel.test W/EGL_emulation﹕ eglSurfaceAttrib not implemented
06-19 06:04:47.126  23858-23907/com.noxel.test W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xb3ffee40, error=EGL_SUCCESS
06-19 06:04:48.491  23858-23858/com.noxel.test I/Choreographer﹕ Skipped 74 frames!  The application may be doing too much work on its main thread.
06-19 06:04:53.728  23858-23903/com.noxel.test D/Volley﹕ [223] BasicNetwork.logSlowRequests: HTTP response for request=<[ ] http://phoneapi.adro.co/Services/AdService.svc/GetAd/ 0x272d3978 NORMAL 1> [lifetime=6813], [size=2397], [rc=400], [retryCount=0]
06-19 06:04:53.729  23858-23903/com.noxel.test E/Volley﹕ [223] BasicNetwork.performRequest: Unexpected response code 400 for http://phoneapi.adro.co/Services/AdService.svc/GetAd/
06-19 06:04:53.731  23858-23858/com.noxel.test D/error﹕ Error
06-19 06:04:53.731  23858-23858/com.noxel.test I/onErrorResponse﹕ com.android.volley.ServerError
06-19 06:04:53.732  23858-23858/com.noxel.test D/Volley﹕ [1] Request.finish: 6817 ms: [ ] http://phoneapi.adro.co/Services/AdService.svc/GetAd/ 0x272d3978 NORMAL 1

1 个答案:

答案 0 :(得分:0)

这是因为您在请求中发送了错误的正文。您的服务器期望“请求”作为帖子正文的根参数。这可以通过将sendObj函数更改为以下内容来实现:

public void sendobj() {
        final JSONObject jsonBody = new JSONObject();
        final JSONObject request = new JSONObject();
        try {
            request.put("DeviceId", "sdasda");
            request.put("AppId", "ECC7BCE40126408386BCFCF8AB9187E7");
            request.put("AdType", "text");
            request.put("Location", "35.7209331,51.472983");
            request.put("UserOperator", "Irancell");
            request.put("Ip", "127.0.0.1");
            request.put("NetworkType", "3G");
            request.put("DeviceType", "Android");
            request.put("DeviceBrand", "Samsung");
            request.put("Width", "0");
            request.put("Height", "0");
            request.put("TestMode", "true");
            jsonBody.put("request", request);
.
.
.