写一段代码,在Android studio中用Java语言访问指定的网站,实现上传和下载数据的功能。
时间: 2023-05-10 18:55:26 浏览: 48
以下是一个简单的示例代码,可以在 Android Studio 中使用 Java 语言访问指定的网站,实现上传和下载数据的功能:
```
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class HttpUrlConnectionExample {
private final String USER_AGENT = "Mozilla/5.0";
public static void main(String[] args) throws Exception {
HttpUrlConnectionExample http = new HttpUrlConnectionExample();
// 发送 HTTP POST 请求
System.out.println("发送 HTTP POST 请求");
http.sendPost();
// 发送 HTTP GET 请求
System.out.println("发送 HTTP GET 请求");
http.sendGet();
}
// HTTP GET 请求
private void sendGet() throws Exception {
String url = "http://www.example.com";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// 设置请求方法
con.setRequestMethod("GET");
// 添加请求头
con.setRequestProperty("User-Agent", USER_AGENT);
int responseCode = con.getResponseCode();
System.out.println("发送 GET 请求,响应码为:" + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// 打印响应结果
System.out.println(response.toString());
}
// HTTP POST 请求
private void sendPost() throws Exception {
String url = "http://www.example.com";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// 设置请求方法
con.setRequestMethod("POST");
// 添加请求头
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
// 发送 POST 请求
String urlParameters = "param1=value1¶m2=value2";
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("发送 POST 请求,响应码为:" + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// 打印响应结果
System.out.println(response.toString());
}
}
```
请注意,这只是一个简单的示例代码,实际上在实现上传和下载数据的功能时,需要根据具体的需求进行修改和完善。