Neshat Neshat - 5 months ago 18
JSON Question

E/Volley﹕ [194] BasicNetwork.performRequest: Unexpected response code 307 for url

I am trying to send a json obj by POST to an api via volley in my android app and capture the json response but i keep getting this error:
E/Volley﹕ [194] BasicNetwork.performRequest: Unexpected response code 307 for http://phoneapi.adro.co/Services/AdService.svc/GetAd .

there is the piece of code that make the request:

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()
{
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";
JsonObjectRequest Req = new JsonObjectRequest(Request.Method.POST, AppConfig.API_URL, jsonBody, 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");
}
}) {

@Override
protected Map<String, String> getParams() throws AuthFailureError
{
// Posting params to register url
Map<String, String> params = new HashMap<String, String>();
params.put("Content-Type", "application/json; charset=utf-8");
return params;
}//

};

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

}//class end


and this is my app controller class:

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 full logcat:

06-17 23:20:54.637 14338-14338/? I/art﹕ Late-enabling -Xcheck:jni
06-17 23:20:54.751 14338-14338/ir.adro.adrosdk I/WebViewFactory﹕ Loading com.android.webview version 37 (eng.buildbot-x86) (code 199997)
06-17 23:20:54.757 14338-14338/ir.adro.adrosdk I/LibraryLoader﹕ Loading: webviewchromium
06-17 23:20:54.758 14338-14338/ir.adro.adrosdk I/LibraryLoader﹕ Time to load native libraries: 1 ms (timestamps 9529-9530)
06-17 23:20:54.758 14338-14338/ir.adro.adrosdk I/LibraryLoader﹕ Expected native library version number "",actual native library version number ""
06-17 23:20:54.766 14338-14338/ir.adro.adrosdk V/WebViewChromiumFactoryProvider﹕ Binding Chromium to main looper Looper (main, tid 1) {39d8cd06}
06-17 23:20:54.767 14338-14338/ir.adro.adrosdk I/LibraryLoader﹕ Expected native library version number "",actual native library version number ""
06-17 23:20:54.767 14338-14338/ir.adro.adrosdk I/chromium﹕ [INFO:library_loader_hooks.cc(106)] Chromium logging enabled: level = 0, default verbosity = 0
06-17 23:20:54.771 14338-14338/ir.adro.adrosdk I/BrowserStartupController﹕ Initializing chromium process, renderers=0
06-17 23:20:54.771 14338-14338/ir.adro.adrosdk W/art﹕ Attempt to remove local handle scope entry from IRT, ignoring
06-17 23:20:54.775 14338-14338/ir.adro.adrosdk W/chromium﹕ [WARNING:resource_bundle.cc(315)] locale_file_path.empty()
06-17 23:20:54.776 14338-14338/ir.adro.adrosdk I/chromium﹕ [INFO:aw_browser_main_parts.cc(63)] Load from apk succesful, fd=32 off=46092 len=2953
06-17 23:20:54.776 14338-14338/ir.adro.adrosdk I/chromium﹕ [INFO:aw_browser_main_parts.cc(78)] Loading webviewchromium.pak from, fd:33 off:228796 len:643667
06-17 23:20:54.780 14338-14358/ir.adro.adrosdk W/AudioManagerAndroid﹕ Requires BLUETOOTH permission
06-17 23:20:54.787 14338-14338/ir.adro.adrosdk D/libEGL﹕ loaded /system/lib/egl/libEGL_emulation.so
06-17 23:20:54.788 14338-14338/ir.adro.adrosdk D/libEGL﹕ loaded /system/lib/egl/libGLESv1_CM_emulation.so
06-17 23:20:54.797 14338-14338/ir.adro.adrosdk D/libEGL﹕ loaded /system/lib/egl/libGLESv2_emulation.so
06-17 23:20:54.806 14338-14338/ir.adro.adrosdk D/﹕ HostConnection::get() New Host Connection established 0xa363fc10, tid 14338
06-17 23:20:54.859 14338-14338/ir.adro.adrosdk W/chromium﹕ [WARNING:mailbox_synchronizer.cc(36)] MailboxSync not supported due to missing EGL image/fence support
06-17 23:20:54.871 14338-14338/ir.adro.adrosdk W/chromium﹕ [WARNING:data_reduction_proxy_settings.cc(403)] SPDY proxy OFF at startup
06-17 23:20:54.881 14338-14338/ir.adro.adrosdk W/art﹕ Attempt to remove local handle scope entry from IRT, ignoring
06-17 23:20:54.882 14338-14338/ir.adro.adrosdk W/AwContents﹕ onDetachedFromWindow called when already detached. Ignoring
06-17 23:20:54.908 14338-14364/ir.adro.adrosdk W/chromium﹕ [WARNING:proxy_service.cc(901)] PAC support disabled because there is no system implementation
06-17 23:20:54.910 14338-14379/ir.adro.adrosdk D/OpenGLRenderer﹕ Render dirty regions requested: true
06-17 23:20:54.912 14338-14338/ir.adro.adrosdk D/Atlas﹕ Validating map...
06-17 23:20:54.980 14338-14379/ir.adro.adrosdk I/OpenGLRenderer﹕ Initialized EGL, version 1.4
06-17 23:20:54.980 14338-14379/ir.adro.adrosdk D/﹕ HostConnection::get() New Host Connection established 0xa1f9fdc0, tid 14379
06-17 23:20:55.005 14338-14379/ir.adro.adrosdk D/OpenGLRenderer﹕ Enabling debug mode 0
06-17 23:20:55.023 14338-14379/ir.adro.adrosdk W/EGL_emulation﹕ eglSurfaceAttrib not implemented
06-17 23:20:55.023 14338-14379/ir.adro.adrosdk W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa1fba7a0, error=EGL_SUCCESS
06-17 23:20:55.235 14338-14377/ir.adro.adrosdk E/Volley﹕ [199] BasicNetwork.performRequest: Unexpected response code 307 for http://phoneapi.adro.co/Services/AdService.svc/GetAd
06-17 23:20:55.235 14338-14338/ir.adro.adrosdk D/error﹕ Error


can anyone tell me why i am keep getting this error?

BNK BNK
Answer

You can avoid 307 reponse code by adding / at the end of your url, i.e. http://phoneapi.adro.co/Services/AdService.svc/GetAd/

Then with the following sample code (I used your jsonBody), you should check your web service more since this code will get 400 reponse code instead

JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, jsonBody, new Response.Listener<JSONObject>() {
    @Override
    public void onResponse(JSONObject response) {
        Log.i("onResponse", response.toString());
    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        Log.i("onErrorResponse", error.toString());
    }
}){
    @Override
    protected VolleyError parseNetworkError(VolleyError volleyError) {
        if(volleyError.networkResponse != null && volleyError.networkResponse.data != null){
            VolleyError error = new VolleyError(new String(volleyError.networkResponse.data));
            volleyError = error;
        }

        return volleyError;
    }
};

When debugging (set breakpoint at VolleyError error = new VolleyError(new String(volleyError.networkResponse.data));), you will get some information such as

The server encountered an error processing the request. The exception message is 'Object reference not set to an instance of an object.'. See server logs for more details. The exception stack trace is: </p> <p> at AdroMobileApi.Services.AdService.GetAd(AdRequest request) at SyncInvokeGetAd(Object , Object[] , Object[] ) at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]&amp; outputs) at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc&amp; rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc&amp; rpc) at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage11(MessageRpc&amp; rpc) at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)</p>