我有一个简单的表单,我需要将其发送到带有参数的URL。
我们说我有一个名为令牌的参数,我想将其发送到example.com/?token=the_token
我不需要处理或获取输出,只需将其发送到此网址即可。
我怎么能这样做?我已经尝试了几个小时来使用URLCONNECTION和HTTPURLCONNECTION,但没有任何效果。
由于我尝试了很多东西而没有任何效果,我正在尝试从头开始。 就是这样:
if (token.isEmpty()) {
getGCMToken();
} else {
//Send the token to example.com/?token=token. The URL will add the token to my database with PHP.
}
请不要使用DefaultHttpClient回复。它已被弃用。
尝试URLConnection():
if (token.isEmpty()) {
getGCMToken();
} else {
//Send the tokeb to example.com/?token=token
URLConnection connection = null;
try {
connection = new URL("mysite.com/send.php?id=my_id").openConnection();
} catch (IOException e) {
e.printStackTrace();
}
connection.setRequestProperty("Accept-Charset", "UTF-8");
try {
InputStream response = connection.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
}
答案 0 :(得分:0)
请使用URLConnection
。
URLConnection connection = new URL(url + "?" + query).openConnection();
connection.setRequestProperty("Accept-Charset", charset);
InputStream response = connection.getInputStream();
答案 1 :(得分:0)
看,我去年建了一个完整的网络/ http通讯课程。我抄袭了处理get(s)的块:
至少导入以下内容:
import java.net.HttpURLConnection;
import java.net.URL;
import java.io.BufferedInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
try{
String mainUrl = "<your_url>";
String query = "?" + "<add_your_params_here>";
URL url = new URL (mainUrl + query);
HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
// If you want to process the response you have to do something the the in InputStream. But ommiting it here, as you said you won't use the response.
}
catch (FileNotFoundException fnf){
Log.e("Incorrect Url", "Resource was not found");
}
catch (Exception e){
}
请记住为Android Manifest xml文件添加INTERNET权限: android.permission.INTERNET
检查此响应是否添加了互联网权限:What permission do I need to access Internet from an android application?