Reputation: 1
I am using IP to transfer data from android to arduino, hopefully I am able to establish the connection with arduino+esp8266 wifi module by choosing its name in the wifi lists in setting since its working as access point. Also through any browser I can send data to the IP by only writing this "192.168.4.1:80?pin=13". However I have a problem with android which is the get not transmitting the request because of its not received by the arduino.
Here is my code, I have also included internet permission in android manifest. What is wrong with it?
final Button image=(Button) findViewById(R.id.button1);
image.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
image.setText("making change");
String urlGET = "http://192.168.4.1:80/?pin=13";
HttpGet getMethod = new HttpGet(urlGET);
// if you are having some headers in your URL uncomment below line
//getMethod.addHeader("Content-Type", "application/form-data");
HttpResponse response = null;
HttpClient httpClient = new DefaultHttpClient();
try {
response = httpClient.execute(getMethod);
int responseCode = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
String responseBody = null;
if (entity != null) {
responseBody = EntityUtils.toString(entity);
//here you get response returned from your server
Log.e("response = ", responseBody);
// response.getEntity().consumeContent();
}
JSONObject jsonObject = new JSONObject(responseBody);
// do whatever you want to do with your json reponse data
}
catch(Exception e)
{
e.printStackTrace();
}
}
});
}
}
Upvotes: 0
Views: 3048
Reputation: 659
1) I think, you already added this permission to manifest file.
<uses-permission android:name="android.permission.INTERNET"/>
2) Activity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ...
// if you perform a networking operation in the main thread
// you must add these lines.
// OR (I prefer) you can do asynchronously.
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
3) Call doTest2() method at button.onclick. I changed Apache HttpClient to java.net.HttpURLConnection.
private void doTest2() {
String urlGET = "http://192.168.4.1:80/?pin=13";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urlGET);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(in);
StringBuffer sb = new StringBuffer();
int data = isr.read();
while (data != -1) {
char current = (char) data;
sb.append(current);
data = isr.read();
}
System.out.print(sb.toString());
JSONObject jsonObject = new JSONObject(sb.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
}
I hope this helps you.
Upvotes: 2