У меня есть эта проблема, которая заставляла меня думать, я использую OkHTTp
для подключения к моей службе WebAPi. Проблема в том, что я продолжаю получать «null», результат на стороне андроида. Вот Android код на стороне:Использование OKHTTP в Android для запроса службы GET из ASP.NET WebApi
public class OkHttpHandlerIncoming extends AsyncTask<String, Void, String> {
OkHttpClient client = new OkHttpClient();
String URL = "http://localhost:8306/api/uconnectservice";
String JsonStringObject;
public OkHttpHandlerIncoming() {
// TODO Auto-generated constructor stub
}
@Override
protected String doInBackground(String... params) {
Request request = new Request.Builder().url(params[0]).build();
// Request request = new
// Request.Builder().url(params[0]).post(formBody).build();
try {
Response response = client.newCall(request).execute();
Log.e("Execute Request", request.toString());
if (!response.isSuccessful())
throw new IOException("Unexpected code " + response.toString());
return response.body().string();
} catch (Exception e) {
}
return null;
}
}
и я сделать вызов из основного потока следующим
public void DATAFROMSERVICE(){
StringBuilder outputText = new StringBuilder("Result:");
OkHttpHandlerIncoming client = new OkHttpHandlerIncoming();
String result = null;
try {
result = client.execute().get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.e("From Service", outputText.append(result + "\n").toString());
}
////////////////////////////////////////
Also here is the code from the server side
public class UConnectServiceController : ApiController
{
private IUconnectRepository _UconnectHandler;
public UConnectServiceController()
{
_UconnectHandler = new UconnectRepository();
}
public UConnectServiceController(IUconnectRepository repository)
{
if (_UconnectHandler == null)
{
throw new ArgumentNullException("repository");
}
_UconnectHandler = repository;
}
/////I am calling this service-> GET api/uconnectservice
public List<AcountTypesRegistered> Get()
{
return _UconnectHandler.GetAll();
}
код продолжается ...
Пожалуйста, может кто-то наставит меня на то, что происходит не так или любые лучшие предложения Thnks
КСТАТИ вот мой кот Войти:
12-13 03:20:54.360: W/System.err(26811): at java.util.concurrent.FutureTask.report(FutureTask.java:93)
12-13 03:20:54.360: W/System.err(26811): at java.util.concurrent.FutureTask.get(FutureTask.java:163)
12-13 03:20:54.360: W/System.err(26811): at android.os.AsyncTask.get(AsyncTask.java:483)
12-13 03:20:54.360: W/System.err(26811): at com.nickSoft.unics_alpha.accountdetails.DATAFROMSERVICE(accountdetails.java:198)
12-13 03:20:54.360: W/System.err(26811): at com.nickSoft.unics_alpha.accountdetails.onCreate(accountdetails.java:120)
12-13 03:20:54.360: W/System.err(26811): at android.app.Activity.performCreate(Activity.java:5231)
12-13 03:20:54.360: W/System.err(26811): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
12-13 03:20:54.360: W/System.err(26811): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2210)
12-13 03:20:54.360: W/System.err(26811): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2296)
12-13 03:20:54.360: W/System.err(26811): at android.app.ActivityThread.access$800(ActivityThread.java:145)
12-13 03:20:54.360: W/System.err(26811): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1243)
12-13 03:20:54.360: W/System.err(26811): at android.os.Handler.dispatchMessage(Handler.java:102)
12-13 03:20:54.360: W/System.err(26811): at android.os.Looper.loop(Looper.java:136)
12-13 03:20:54.360: W/System.err(26811): at android.app.ActivityThread.main(ActivityThread.java:5136)
12-13 03:20:54.360: W/System.err(26811): at java.lang.reflect.Method.invokeNative(Native Method)
12-13 03:20:54.360: W/System.err(26811): at java.lang.reflect.Method.invoke(Method.java:515)
12-13 03:20:54.360: W/System.err(26811): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:819)
12-13 03:20:54.360: W/System.err(26811): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:635)
12-13 03:20:54.360: W/System.err(26811): at dalvik.system.NativeStart.main(Native Method)
12-13 03:20:54.360: W/System.err(26811): Caused by: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
12-13 03:20:54.360: W/System.err(26811): at com.nickSoft.Connections.OkHttpHandlerIncoming.doInBackground(OkHttpHandlerIncoming.java:53)
12-13 03:20:54.360: W/System.err(26811): at com.nickSoft.Connections.OkHttpHandlerIncoming.doInBackground(OkHttpHandlerIncoming.java:1)
12-13 03:20:54.360: W/System.err(26811): at android.os.AsyncTask$2.call(AsyncTask.java:288)
12-13 03:20:54.360: W/System.err(26811): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
12-13 03:20:54.360: W/System.err(26811): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
12-13 03:20:54.360: W/System.err(26811): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
12-13 03:20:54.360: W/System.err(26811): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
12-13 03:20:54.360: W/System.err(26811): at java.lang.Thread.run(Thread.java:841)
12-13 03:20:54.360: E/From Service(26811): Result:null
12-13 03:20:54.360: W/dalvikvm(26811): threadid=11: thread exiting with uncaught exception (group=0x415ced88)
12-13 03:20:54.360: E/test(26811): Exception
12-13 03:20:54.370: E/AndroidRuntime(26811): FATAL EXCEPTION: AsyncTask #1
12-13 03:20:54.370: E/AndroidRuntime(26811): Process: com.nickSoft.unics_alpha, PID: 26811
12-13 03:20:54.370: E/AndroidRuntime(26811): java.lang.RuntimeException: An error occured while executing doInBackground()
12-13 03:20:54.370: E/AndroidRuntime(26811): at android.os.AsyncTask$3.done(AsyncTask.java:300)
12-13 03:20:54.370: E/AndroidRuntime(26811): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
12-13 03:20:54.370: E/AndroidRuntime(26811): at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
12-13 03:20:54.370: E/AndroidRuntime(26811): at java.util.concurrent.FutureTask.run(FutureTask.java:242)
12-13 03:20:54.370: E/AndroidRuntime(26811): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
12-13 03:20:54.370: E/AndroidRuntime(26811): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
12-13 03:20:54.370: E/AndroidRuntime(26811): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
12-13 03:20:54.370: E/AndroidRuntime(26811): at java.lang.Thread.run(Thread.java:841)
12-13 03:20:54.370: E/AndroidRuntime(26811): Caused by: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
12-13 03:20:54.370: E/AndroidRuntime(26811): at com.nickSoft.Connections.OkHttpHandlerIncoming.doInBackground(OkHttpHandlerIncoming.java:53)
12-13 03:20:54.370: E/AndroidRuntime(26811): at com.nickSoft.Connections.OkHttpHandlerIncoming.doInBackground(OkHttpHandlerIncoming.java:1)
12-13 03:20:54.370: E/AndroidRuntime(26811): at android.os.AsyncTask$2.call(AsyncTask.java:288)
12-13 03:20:54.370: E/AndroidRuntime(26811): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
12-13 03:20:54.370: E/AndroidRuntime(26811): ... 4 more
/// ПОСЛЕ CODE EDIT ПОЛУЧИТЬ ЭТУ LogCat ////////////////
12-13 03:58:36.640: I/ActivityManager(28324): Timeline: Activity_idle id: [email protected] time:12169583
12-13 03:59:30.560: W/System.err(29371): java.net.ConnectException: Failed to connect to localhost/127.0.0.1:8306
12-13 03:59:30.560: W/System.err(29371): at okhttp3.internal.connection.RealConnection.connectSocket(RealConnection.java:189)
12-13 03:59:30.560: W/System.err(29371): at okhttp3.internal.connection.RealConnection.buildConnection(RealConnection.java:173)
12-13 03:59:30.560: W/System.err(29371): at okhttp3.internal.connection.RealConnection.connect(RealConnection.java:114)
12-13 03:59:30.560: W/System.err(29371): at okhttp3.internal.connection.StreamAllocation.findConnection(StreamAllocation.java:193)
12-13 03:59:30.560: W/System.err(29371): at okhttp3.internal.connection.StreamAllocation.findHealthyConnection(StreamAllocation.java:129)
12-13 03:59:30.560: W/System.err(29371): at okhttp3.internal.connection.StreamAllocation.newStream(StreamAllocation.java:98)
12-13 03:59:30.570: W/System.err(29371): at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:42)
12-13 03:59:30.570: W/System.err(29371): at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
12-13 03:59:30.570: W/System.err(29371): at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
12-13 03:59:30.570: W/System.err(29371): at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:109)
12-13 03:59:30.570: W/System.err(29371): at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
12-13 03:59:30.570: W/System.err(29371): at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
12-13 03:59:30.570: W/System.err(29371): at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
12-13 03:59:30.570: W/System.err(29371): at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
12-13 03:59:30.570: W/System.err(29371): at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:124)
12-13 03:59:30.570: W/System.err(29371): at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
12-13 03:59:30.570: W/System.err(29371): at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
12-13 03:59:30.570: W/System.err(29371): at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:170)
12-13 03:59:30.570: W/System.err(29371): at okhttp3.RealCall.access$100(RealCall.java:33)
12-13 03:59:30.570: W/System.err(29371): at okhttp3.RealCall$AsyncCall.execute(RealCall.java:120)
12-13 03:59:30.570: W/System.err(29371): at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
12-13 03:59:30.570: W/System.err(29371): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
12-13 03:59:30.570: W/System.err(29371): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
12-13 03:59:30.570: W/System.err(29371): at java.lang.Thread.run(Thread.java:841)
Я настоятельно рекомендую проверить https://square.github.io/retrofit/. Он использует OkHTTP под капотом по умолчанию, но обеспечивает очень простое взаимодействие с api. – Orbit
thnx @ Orbit, глядя в него – user3015410
Вы молчаливо глотаете все исключения с помощью 'catch (Exception e) {}' вам следует добавить 'e.printStackTrace();' там, чтобы помочь вам разобраться, что происходит с вашим вызовом – iagreen