[英]sending and receiving data using android application, arduino, and esp8266 wifi module
[英]sending data through wifi using get by IP from an android cell phone to arduino+esp8266
我正在使用IP將數據從android傳輸到arduino,希望我能夠通過在設置中的wifi列表中選擇其名稱來建立與arduino + esp8266 wifi模塊的連接,因為它起着接入點的作用。 同樣,通過任何瀏覽器,我只要編寫“ 192.168.4.1:80?pin=13”就可以將數據發送到IP。 但是我對android有一個問題,因為arduino沒有接收到它,所以無法傳輸請求。
這是我的代碼,我還在Android清單中添加了Internet權限。 怎么了
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();
}
}
});
}
}
1)我想,您已經將此權限添加到了清單文件中。
<uses-permission android:name="android.permission.INTERNET"/>
2)活動
@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)在button.onclick上調用doTest2()方法。 我將Apache HttpClient更改為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();
}
}
}
我希望這可以幫助你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.