SOAP call from Android with KSoap2 to .net WebServer - android

Good day everyone.
I'm trying to do a SOAP call to a .net WebServer running locally, but I think I'm missing something. The Android code seems fine to me. Maybe the SOAP request is wrong...
This is what the webserver gives for the method I'm trying to call:
POST /WebAvanza/WebAvanzaInterface.asmx HTTP/1.1
Host: localhost
Content-Type: application/soap+xml; charset=utf-8
Content-Length: length
<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
<soap12:Body>
<InitTransazione xmlns="http://tempuri.org/">
<ip>string</ip>
<codice>string</codice>
</InitTransazione>
</soap12:Body>
</soap12:Envelope>
and this is what i wrote so far:
private String InitTransaction(String command){
String NAMESPACE = "http://tempuri.org/";
String METHOD_NAME = "InitTransazione";
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("ip", ipAddress);
request.addProperty("codice", command);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE httpTransport = new HttpTransportSE(URL);
httpTransport.debug = true;
String SOAP_ACTION = NAMESPACE + METHOD_NAME;
Object result = null;
try {
httpTransport.call(SOAP_ACTION, envelope);
result = envelope.getResponse();
}
catch(Exception e)
{
e.printStackTrace();
}
return String.valueOf(result);
}
URL is http://192.168.168.24/WebAvanza/WebAvanzaInterface.asmx, the address refers to the machine where the server is running.
I only get an exception after executing httpTransport.call.
This is the StackTrace (if anybosy needs it)
W/System.err: android.os.NetworkOnMainThreadException
W/System.err: at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1528)
W/System.err: at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:389)
W/System.err: at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:230)
W/System.err: at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:212)
W/System.err: at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:436)
W/System.err: at java.net.Socket.connect(Socket.java:621)
W/System.err: at com.android.okhttp.internal.Platform.connectSocket(Platform.java:145)
W/System.err: at com.android.okhttp.internal.io.RealConnection.connectSocket(RealConnection.java:141)
W/System.err: at com.android.okhttp.internal.io.RealConnection.connect(RealConnection.java:112)
W/System.err: at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:184)
W/System.err: at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:126)
W/System.err: at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:95)
W/System.err: at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:281)
W/System.err: at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:224)
W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:461)
W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:127)
W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:258)
W/System.err: at org.ksoap2.transport.ServiceConnectionSE.openOutputStream(ServiceConnectionSE.java:130)
W/System.err: at org.ksoap2.transport.HttpTransportSE.sendData(HttpTransportSE.java:295)
W/System.err: at org.ksoap2.transport.HttpTransportSE.call(HttpTransportSE.java:184)
W/System.err: at org.ksoap2.transport.HttpTransportSE.call(HttpTransportSE.java:118)
W/System.err: at org.ksoap2.transport.HttpTransportSE.call(HttpTransportSE.java:113)
W/System.err: at com.infovision.elcam_02.Operations$override.InitTransaction(Operations.java:64)
W/System.err: at com.infovision.elcam_02.Operations$override.InitOperation(Operations.java:40)
W/System.err: at com.infovision.elcam_02.Operations$override.access$dispatch(Unknown Source:49)
W/System.err: at com.infovision.elcam_02.Operations.InitOperation(Unknown Source:15)

I found out that the problem was in the server and the code was fine...
Goddamn I spent almost 5 hours behind this .__.

Checking your code I think the main problem is because you are not executing Okhttpclient in async thread.
I think the problem should be solved if you run the code using enqueue method of the Okhttpclient.
client.newCall(request).enqueue(new Callback() {
#Override public void onFailure(Call call, IOException e) {
//Exception here
}
#Override public void onResponse(Call call, Response response) throws IOException {
try (ResponseBody responseBody = response.body()) {
/*
* Handle your response here :
* Do whatever you want if the response.isSuccesful or not
*/
}
});
I hope it helps you.

Related

How to resolve SSL Handshake failure between Android app and Dropwizard server

I am trying to make an HTTP request from an Android app to a Dropwizard server that I have created, and am seeing an SSL handshake failure due to WRONG_VERSION_NUMBER. How do I make them work together?
As far as SSL or other authentication goes, I am using default technologies for both Dropwizard and Android--haven't configured anything for either. I tried setting different protocols on the server with JVM arguments
-Dhttps.protocols=TLSv1.2,TLSv1.1,TLSv1
But that didn't seem to make any difference. Since I haven't set anything, I don't know what each side is using by default.
This is how I am making the connection inside my app:
private class ScanRetreiver extends AsyncTask<String, Void, String> {
#Override
public String doInBackground(String... args) {
String resultString = null;
try {
//send GET request to REST API for list of items
URL url = new URL(args[0]);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
resultString = convertStreamToString(in);
} finally {
urlConnection.disconnect();
//display items--this means generating an arbitrary list of elements. should be fun
//optionally, elements can be expandable
}
} catch (Exception e) {
e.printStackTrace();
}
return resultString;
}
I see the Exception at the line where I try to call getInputStream on the urlConnection.
This is the error message that I see on the App side of things:
W/System.err: javax.net.ssl.SSLHandshakeException: Handshake failed
W/System.err: at com.android.org.conscrypt.ConscryptFileDescriptorSocket.startHandshake(ConscryptFileDescriptorSocket.java:302)
W/System.err: at com.android.okhttp.internal.io.RealConnection.connectTls(RealConnection.java:1480)
W/System.err: at com.android.okhttp.internal.io.RealConnection.connectSocket(RealConnection.java:1424)
W/System.err: at com.android.okhttp.internal.io.RealConnection.connect(RealConnection.java:1368)
W/System.err: at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:219)
W/System.err: at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:142)
W/System.err: at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:104)
W/System.err: at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:392)
W/System.err: at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:325)
W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:470)
W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:416)
W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:244)
W/System.err: at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getInputStream(DelegatingHttpsURLConnection.java:210)
W/System.err: at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:26)
W/System.err: at com.example.myfirstapp.ScanResultActivity$ScanRetreiver.doInBackground(ScanResultActivity.java:55)
W/System.err: at com.example.myfirstapp.ScanResultActivity$ScanRetreiver.doInBackground(ScanResultActivity.java:45)
W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:333)
W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:266)
W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
W/System.err: at java.lang.Thread.run(Thread.java:764)
W/System.err: Caused by: javax.net.ssl.SSLProtocolException: SSL handshake aborted: ssl=0x73e73f3908: Failure in SSL library, usually a protocol error
error:100000f7:SSL routines:OPENSSL_internal:WRONG_VERSION_NUMBER (external/boringssl/src/ssl/tls_record.cc:242 0x73f51bfecf:0x00000000)
W/System.err: at com.android.org.conscrypt.NativeCrypto.SSL_do_handshake(Native Method)
W/System.err: at com.android.org.conscrypt.NativeSsl.doHandshake(NativeSsl.java:383)
W/System.err: at com.android.org.conscrypt.ConscryptFileDescriptorSocket.startHandshake(ConscryptFileDescriptorSocket.java:231)
... 21 more

java.net.UnknownHostException: Host is unresolved SOCKS proxy

I setup tor on a specific port and want to access the website through that port. The below code works perfectly in Android 7.0 but it gives below error in android 6.0. What may be the issue? The tor service successfully running at a specific port I am sending a request to.
Running sample code of this library (https://github.com/jehy/Tor-Onion-Proxy-Library)
Error
java.net.UnknownHostException: Host is unresolved: google.com
W/System.err: at java.net.Socket.connect(Socket.java:893)
W/System.err: at
cz.msebera.android.httpclient.conn.socket.PlainConnectionSocketFactory.connectSocket(PlainConnectionSocketFactory.java:74)
W/System.err: at
com.example.nandan.sampletorproxyapp.MyConnectionSocketFactory.connectSocket(MyConnectionSocketFactory.java:33)
W/System.err: at
cz.msebera.android.httpclient.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:134)
W/System.err: at
cz.msebera.android.httpclient.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:353)
W/System.err: at
cz.msebera.android.httpclient.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:380)
W/System.err: at
cz.msebera.android.httpclient.impl.execchain.MainClientExec.execute(MainClientExec.java:236)
W/System.err: at
cz.msebera.android.httpclient.impl.execchain.ProtocolExec.execute(ProtocolExec.java:184)
W/System.err: at
cz.msebera.android.httpclient.impl.execchain.RetryExec.execute(RetryExec.java:88)
W/System.err: at
cz.msebera.android.httpclient.impl.execchain.RedirectExec.execute(RedirectExec.java:110)
W/System.err: at
cz.msebera.android.httpclient.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184)
W/System.err: at
cz.msebera.android.httpclient.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
W/System.err: at
cz.msebera.android.httpclient.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:55)
W/System.err: at
com.example.nandan.sampletorproxyapp.MainActivity$TorTask.doInBackground(MainActivity.java:85)
W/System.err: at
com.example.nandan.sampletorproxyapp.MainActivity$TorTask.doInBackground(MainActivity.java:60)
W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:295)
W/System.err: at
java.util.concurrent.FutureTask.run(FutureTask.java:237) W/System.err:
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
W/System.err: at
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
W/System.err: at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
W/System.err: at java.lang.Thread.run(Thread.java:818)
Main Activity
HttpClient httpClient = getNewHttpClient();
int port = onionProxyManager.getIPv4LocalHostSocksPort();
InetSocketAddress socksaddr = new InetSocketAddress("127.0.0.1", port);
HttpClientContext context = HttpClientContext.create();
context.setAttribute("socks.address", socksaddr);
HttpGet httpGet = new HttpGet("http://google.co.in");
HttpResponse httpResponse = httpClient.execute(httpGet, context); // GETTING ERROR HERE
static class FakeDnsResolver implements DnsResolver {
#Override
public InetAddress[] resolve(String host) throws UnknownHostException {
return new InetAddress[] { InetAddress.getByAddress(new byte[] { 1, 1, 1, 1 }) };
}
}
public HttpClient getNewHttpClient() {
Registry<ConnectionSocketFactory> reg = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", new MyConnectionSocketFactory())
.build();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(reg,new FakeDnsResolver());
return HttpClients.custom()
.setConnectionManager(cm)
.build();
}
MyConnectionSocketFactory.java
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.Socket;
import cz.msebera.android.httpclient.HttpHost;
import cz.msebera.android.httpclient.conn.socket.PlainConnectionSocketFactory;
import cz.msebera.android.httpclient.protocol.HttpContext;
public class MyConnectionSocketFactory extends PlainConnectionSocketFactory {
#Override
public Socket createSocket(final HttpContext context) {
InetSocketAddress socksaddr = (InetSocketAddress) context.getAttribute("socks.address");
Proxy proxy = new Proxy(Proxy.Type.SOCKS, socksaddr);
return new Socket(proxy);
}
#Override
public Socket connectSocket(
int connectTimeout,
Socket socket,
final HttpHost host,
final InetSocketAddress remoteAddress,
final InetSocketAddress localAddress,
final HttpContext context) throws IOException{
InetSocketAddress unresolvedRemote = InetSocketAddress
.createUnresolved(host.getHostName(), remoteAddress.getPort());
return super.connectSocket(connectTimeout, socket, host, unresolvedRemote, localAddress, context);
}
}
Try changing
HttpGet httpGet = new HttpGet("http:google.co.in");
to
HttpGet httpGet = new HttpGet("http://google.co.in");
or
URI uri = new URIBuilder()
.setScheme("http")
.setHost("google.co.in")
.build();
HttpGet httpGet = new HttpGet(uri);
updated - try this
HttpHost target = new HttpHost("google.co.in", 80, "http");
HttpGet httpGet = new HttpGet("/");
HttpResponse httpResponse = httpClient.execute(target, httpGet, context);
If it don't work im not too sure. Maybe try this link hopefully this helps How to use HttpClientBuilder with Http proxy?

AsyncTask - java.net.SocketException: Connection reset

I have an AsyncTask to fetch JSON data from a DB on my server. It works well normally but is failing sometimes with the below error. It seems like this happens when I keep the app idle but open for some time and then make a request.
doInBackground Method
try {
URL url = new URL(url_get_initial_posts);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
String data_string_language = URLEncoder.encode("selected_language","UTF-8")+"="+URLEncoder.encode(arg_language,"UTF-8")
+"&"+URLEncoder.encode("app_time","UTF-8")+"="+URLEncoder.encode(String.valueOf(arg_app_time),"UTF-8");
bufferedWriter.write(data_string_language);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
while ((JSON_INITIAL_POST = bufferedReader.readLine()) != null) {
stringBuilder.append(JSON_INITIAL_POST + "\n");
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return stringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
This line in the error
W/System.err: at com.indiparent.android.indiparent.PostTab$BackgroundJSONPosts.doInBackground(PostTab.java:343)
links to
InputStream inputStream = httpURLConnection.getInputStream();
Error
W/System.err: java.net.SocketException: Connection reset
W/System.err: at java.net.SocketInputStream.read(SocketInputStream.java:209)
W/System.err: at java.net.SocketInputStream.read(SocketInputStream.java:139)
W/System.err: at com.android.okhttp.okio.Okio$2.read(Okio.java:136)
W/System.err: at com.android.okhttp.okio.AsyncTimeout$2.read(AsyncTimeout.java:211)
W/System.err: at com.android.okhttp.okio.RealBufferedSource.indexOf(RealBufferedSource.java:306)
W/System.err: at com.android.okhttp.okio.RealBufferedSource.indexOf(RealBufferedSource.java:300)
W/System.err: at com.android.okhttp.okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:196)
W/System.err: at com.android.okhttp.internal.http.Http1xStream.readResponse(Http1xStream.java:186)
W/System.err: at com.android.okhttp.internal.http.Http1xStream.readResponseHeaders(Http1xStream.java:127)
W/System.err: at com.android.okhttp.internal.http.HttpEngine.readNetworkResponse(HttpEngine.java:737)
W/System.err: at com.android.okhttp.internal.http.HttpEngine.readResponse(HttpEngine.java:609)
W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:471)
W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:407)
W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:244)
W/System.err: at com.indiparent.android.indiparent.PostTab$BackgroundJSONPosts.doInBackground(PostTab.java:343)
W/System.err: at com.indiparent.android.indiparent.PostTab$BackgroundJSONPosts.doInBackground(PostTab.java:308)
W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:333)
W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:266)
W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
W/System.err: at java.lang.Thread.run(Thread.java:764)
Extra Info - This is not the only Asynctask in the application. There are more in other activities and fragments. For example - if AsynckTask of Activity 2 throws this error then if I come back to Activity 1 then its AsyncTask also does not work.
Am I supposed to do something here or on the server side? Appreciate any help here.

java.net.UnknownHostException: Unable to resolve host "414.shtml": No address associated with hostname for Retrofit api hitting

I'm using retrofit2 for api hitting and parameter is String type.
When string value is small then it's working fine but when string data is large then getting following exception.
java.net.UnknownHostException: Unable to resolve host "414.shtml": No address associated with hostname
at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:125)
at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:74)
at java.net.InetAddress.getAllByName(InetAddress.java:752)
at okhttp3.Dns$1.lookup(Dns.java:39)
at okhttp3.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:173)
at okhttp3.internal.http.RouteSelector.nextProxy(RouteSelector.java:139)
at okhttp3.internal.http.RouteSelector.next(RouteSelector.java:81)
at okhttp3.internal.http.StreamAllocation.findConnection(StreamAllocation.java:172)
at okhttp3.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:123)
at okhttp3.internal.http.StreamAllocation.newStream(StreamAllocation.java:93)
at okhttp3.internal.http.HttpEngine.connect(HttpEngine.java:296)
at okhttp3.internal.http.HttpEngine.sendRequest(HttpEngine.java:248)
at okhttp3.RealCall.getResponse(RealCall.java:243)
at okhttp3.RealCall$ApplicationInterceptorChain.proceed(RealCall.java:201)
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:163)
at okhttp3.RealCall.access$100(RealCall.java:30)
at okhttp3.RealCall$AsyncCall.execute(RealCall.java:127)
at okhttp3.internal.NamedRunnable.run(NamedRunnable.java:32)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:762)
Caused by: android.system.GaiException: android_getaddrinfo failed: EAI_NODATA (No address associated with hostname)
at libcore.io.Posix.android_getaddrinfo(Native Method)
at libcore.io.ForwardingOs.android_getaddrinfo(ForwardingOs.java:55)
at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:106)
enter code here
I was sending json in parameters, therefore I was getting java.net.UnknownHostException: Unable to resolve host "414.shtml".
For that we have to send json in request body.
Following code for send json using request body.
RequestBody body = null;
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("data", data);
body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonObject.toString());
} catch (JSONException e) {
e.printStackTrace();
}
public interface ApiInterface {
#POST
Call<DemoResponse> apitest(#Url String url, #Body RequestBody body);
}

Google Maps Geocoding API request issue in Android Studio with okHTTP

I am trying to get JSON from Google Maps Geocoding API using okHTTP (http://square.github.io/okhttp/) in Android Studio and my program crashes with the following error log:
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:4020)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at android.view.View$1.onClick(View.java:4015)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
at java.net.InetAddress.getAllByName(InetAddress.java:215)
at com.squareup.okhttp.Dns$1.lookup(Dns.java:39)
at com.squareup.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:184)
at com.squareup.okhttp.internal.http.RouteSelector.nextProxy(RouteSelector.java:153)
at com.squareup.okhttp.internal.http.RouteSelector.next(RouteSelector.java:95)
at com.squareup.okhttp.internal.http.HttpEngine.createNextConnection(HttpEngine.java:345)
at com.squareup.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:328)
at com.squareup.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:246)
at com.squareup.okhttp.Call.getResponse(Call.java:276)
at com.squareup.okhttp.Call$ApplicationInterceptorChain.proceed(Call.java:234)
at com.squareup.okhttp.Call.getResponseWithInterceptorChain(Call.java:196)
at com.squareup.okhttp.Call.execute(Call.java:79)
...
The last error log's Caused by gives a hint that the issue might be in okHTTP security communication. I did not set it up because I can not figure out whether I need to do it at all and how to do it then. This page might be relevant, but I am not sure: https://github.com/square/okhttp/wiki/HTTPS
Communication with Google Geocoding API happens through https.
Here is the code I am trying to use:
OkHttpClient client = new OkHttpClient();
String strAddress = "Winnetka";
String googleMapsAPIKey = this.getString(R.string.google_maps_api_key);
String url = null;
try {
url = "https://maps.googleapis.com/maps/api/geocode/json" +
"?address=" + URLEncoder.encode(strAddress, "UTF-8") + "&key=" + googleMapsAPIKey;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
}
Request request = new Request.Builder()
.url(url)
.build();
try {
Response response = client.newCall(request).execute();
} catch (IOException e) {
e.printStackTrace();
return null;
}
It fails on the line Response response = client.newCall(request).execute();
I logged out the url that I formed and it looks identical to the one that is used in the examples on the API's website (https://developers.google.com/maps/documentation/geocoding/intro):
https://maps.googleapis.com/maps/api/geocode/json?address=Winnetka&key=...
Could anyone, please, help?
Your issue: Caused by: android.os.NetworkOnMainThreadException
You should use OkHttps async method:
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException throwable) {
throwable.printStackTrace();
}
#Override
public void onResponse(Response response) throws IOException {
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
}
// Do Stuff
});

Categories

Resources