我正在使用IP将数据从android传输到arduino,希望我能够通过在设置中的wifi列表中选择其名称来建立与arduino + esp8266 wifi模块的连接,因为它作为接入点工作。同样通过任何浏览器,我只需编写这个" 192.168.4.1:80?pin = 13"即可将数据发送到IP。但是我有一个android的问题,因为它没有被arduino接收,所以没有传输请求。
这是我的代码,我还在android清单中包含了互联网权限。这有什么问题?
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();
}
}
});
}
}
答案 0 :(得分:0)
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();
}
}
}
我希望这会对你有所帮助。