user6485186 user6485186 - 5 months ago 918
Android Question

BasicNetwork.performRequest: Unexpected response code 400 for URL (POST) volley

I am developing an android app that sends a

json object
to an api url and should receive a json object as a
response
but i keep getting this
error
:

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

I am using
volley
.

My
json object
to
request
is supposed to be like this:

"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
}


these are my codes:

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


and this is my app controller :

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);
}
}
}


and this is my 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

Answer

This because you are sending wrong body in the request. Your server is expecting "request" as the root parameter of the post body. This can be achieved by changing you sendObj function to following :

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);
.
.
.
Comments