好吧,所以我有以下情况,我有一个Java应用程序,用户可以登录,一旦他们这样做会产生一个随机密钥,我希望发送这个密钥到我的网站使用http请求。Android的HTTP请求与发布数据
在网络端,我将它插入到数据库中供以后使用,这已经在工作。
现在在这个时刻我非常喜欢java端。我使用下面的代码来尝试HTTP请求:
private void startRegistration(String username, String password) {
String myRandomString = randomString(6);
String deviceId = "abc";
startToast(myRandomString);
try {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
insertDevice(myRandomString, deviceId);
} catch (IOException e) {
e.printStackTrace();
}
}
@TargetApi(Build.VERSION_CODES.KITKAT)
public void insertDevice(String randomString, String deviceId) throws IOException {
// String urlParameters = "key=" + randomString + "&device_id="+ deviceId;
// byte[] postData = urlParameters.getBytes(StandardCharsets.UTF_8);
// int postDataLength = postData.length;
String request = "http://website.com/test";
URL url = new URL(request);
HttpURLConnection conn= (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setInstanceFollowRedirects(false);
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("charset", "utf-8");
// conn.setRequestProperty("Content-Length", Integer.toString(postDataLength));
conn.setUseCaches(false);
try(DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
// wr.write(postData);
Context context = getApplicationContext();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, "test", duration);
toast.show();
}
}
在网络方面我有一个路径设置为抓住这一请求,并简单的抛出一个日志::信息,以便我可以检查是否请求甚至还未获得在那里,这看起来像如下:
public function create() {
Log::info('I got here, hurray!');
}
现在当我打的网址在浏览器中,我可以看到日志出现,当我用我的应用程序,我不知道。但是也没有错误。
最后,我想使用POST请求,并将随机密钥和设备ID都发送到网站。任何帮助,非常感谢
您可以使用[OkHttp(HTTP://方.github.io/okhttp /)库。这会让你的任务更容易。 – pike
http://stackoverflow.com/questions/11766878/sending-files-using-post-with-httpurlconnection下面的链接将帮助你 – Anjali
你似乎没有调用'conn.connect()'... – injecteer