0
我想通过使用AsyncTask
将数据发布到我的localhost
,可以通过Genymotion的10.0.3.2:8787
和Localhost的127.0.0.1:8787
访问。但是,它似乎没有发布任何内容。以下是我的代码;Android Studio HttpURLConnection不发布数据
private class LocationUpdateTask extends AsyncTask<String, Void, Void> {
@Override
protected Void doInBackground(String... params) {
String _url = "http://10.0.3.2:8787/user_locations/save";
HttpURLConnection httpClient = null;
try {
for (int i = 0; i < params.length; i++) {
String urlParameters = params[i];
System.out.println(urlParameters); // Prints fine here.
URL url = new URL(_url);
httpClient = (HttpURLConnection) url.openConnection();
httpClient.setRequestMethod("POST");
httpClient.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
httpClient.setRequestProperty("Content-Language", "en-US");
httpClient.setUseCaches(false);
httpClient.setDoInput(true);
httpClient.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream(httpClient.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (httpClient != null) {
httpClient.disconnect();
}
}
return null;
}
}
public class LocationUpdaterListener implements LocationListener
{
@Override
public void onLocationChanged(Location location) {
//String text = "Lat: " + location.getLatitude() + "\nLong: " + location.getLongitude();
//Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();
HashMap<String, String> postDataParams=new HashMap<String, String>();
postDataParams.put("fuid", profileId);
postDataParams.put("lat", String.valueOf(location.getLatitude()));
postDataParams.put("lng", String.valueOf(location.getLongitude()));
postDataParams.put("alt", String.valueOf(location.getAltitude()));
postDataParams.put("br", String.valueOf(location.getBearing()));
postDataParams.put("acc", String.valueOf(location.getAccuracy()));
String urlParameters = null;
try {
urlParameters = "fuid=" + URLEncoder.encode(postDataParams.get("fuid"), "UTF-8")+
"&lat="+URLEncoder.encode(postDataParams.get("lat"), "UTF-8")+
"&lng="+URLEncoder.encode(postDataParams.get("lng"), "UTF-8")+
"&alt="+URLEncoder.encode(postDataParams.get("alt"), "UTF-8")+
"&br="+URLEncoder.encode(postDataParams.get("br"), "UTF-8")+
"&acc="+URLEncoder.encode(postDataParams.get("acc"), "UTF-8");
}
catch (Exception e) {
e.printStackTrace();
}
finally {
if (urlParameters != null){
new LocationUpdateTask().execute(urlParameters);
}
}
}
@Override
public void onProviderDisabled(String provider) { }
@Override
public void onProviderEnabled(String provider) { }
@Override
public void onStatusChanged(String provider, int status, Bundle extras) { }
}
没有任何异常抛出。如果我通常通过浏览器访问并传递参数,它工作得很好。所以,我认为我的代码一定是错的。
那么,这是错误的我的代码?或者我应该尝试看看为什么这不起作用?
任何建议表示赞赏。
的服务器是在Windows?尝试从您的设备/模拟器Web浏览器进行访问。检查你的防火墙。 –
@dieter_h它在Ubuntu 14.04上。我试着用模拟器的浏览器和ubuntu的浏览器直接链接参数,它们都工作得很好。 – choz
您不在'HttpURLConnection'中使用'urlParameters' –