我正在尝试通过POST将json obj发送到api,通过我的Android应用程序中的截击并捕获json响应,但我一直收到此错误: E / Volley:[194] BasicNetwork.performRequest:http://phoneapi.adro.co/Services/AdService.svc/GetAd的意外响应代码307。
有一段代码发出请求:
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
这是我的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-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
谁能告诉我为什么我会一直收到这个错误?
答案 0 :(得分:5)
您可以在网址末尾添加/
来避免 307 响应代码,即http://phoneapi.adro.co/Services/AdService.svc/GetAd/
然后使用以下示例代码(我使用了您的jsonBody
),您应该检查您的网络服务,因为此代码将获得 400 响应代码
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;
}
};
调试时(在VolleyError error = new VolleyError(new String(volleyError.networkResponse.data));
处设置断点),您将获得一些信息,例如
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[]& outputs)
at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage11(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)</p>
答案 1 :(得分:1)
响应代码307 表示临时重定向。
请检查您的服务器端是否存在此问题。
更多说明:
服务器将此响应发送给指示客户端以获取请求 资源到另一个URI,使用与先前请求相同的方法。这个 具有与302 Found HTTP响应代码相同的语义 用户代理不得更改所使用的HTTP方法的异常:if 在第一个请求中使用了POST,必须在中使用POST 第二次请求。
有关详细信息,请参阅:Response codes for HTTP