java - 如何从 Android 发出 http 请求?
问题描述
我正在尝试制作一个移动应用程序,我目前正在创建用于与服务器通信的 api。我的代码在普通的 maven 项目上运行良好,但是当我将它添加到我的 android studio 项目时,当我尝试从连接输入流中读取时出现错误。
package client;
import org.json.JSONObject;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
public class CCH {
//static private String host = "http://localhost:8080";
static private String host ="https://radiant-bayou-97811.herokuapp.com";
//GET REQUESTS
public static Integer login(String username, String password){
String tempurl = host + "/api/user/login/" + username + "/" + password;
JSONObject jsonObject = getRequest(tempurl);
if(jsonObject.has("login"))
if(jsonObject.get("login").equals("true"))
return 1;
else
return 0;
else
return 0;
}
public static JSONObject getPacient(String username){
String tempurl = host + "/api/user/getPacient/" + username;
return getRequest(tempurl);
}
public static JSONObject getIstoric(String username){
String tempurl = host + "/api/user/pacient/istoric/" + username;
return getRequest(tempurl);
}
public static JSONObject getDiagnostic(String username){
String tempurl = host + "/api/user/pacient/diagnostic/" + username;
return getRequest(tempurl);
}
//POST REQUESTS
public static void sendData(String username,String time,String puls,String calorii,String nr_pasi,String nivel_oxigen,String calitate_somn){
String tempurl = host+ "/api/user/pacient/importData";
JSONObject jsonObject = new JSONObject();
jsonObject.append("username",username);
jsonObject.append("time",time);
jsonObject.append("puls",puls);
jsonObject.append("calorii",calorii);
jsonObject.append("nr_pasi",nr_pasi);
jsonObject.append("nivel_oxigen",nivel_oxigen);
jsonObject.append("calitate_somn",calitate_somn);
postRequest(tempurl,jsonObject);
}
public static JSONObject getRequest(String URL){
JSONObject response = null;
HttpURLConnection connection = null;
try {
URL url = new URL(URL);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
response = new JSONObject(readFromConnection(connection));
}catch (Exception e){
response = new JSONObject();
response.append("Error!","Error on the client side contact the admin!");
response.append("Error!!",e.getCause());
e.printStackTrace();
}
finally {
connection.disconnect();
return response;
}
}
public static void postRequest(String URL,JSONObject jsonObject){
HttpURLConnection connection = null;
try{
URL url = new URL(URL);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
// connection.setRequestProperty("Accept", "application/json");
connection.setDoOutput(true);
OutputStream os = connection.getOutputStream();
os.write(createJson(jsonObject).getBytes());
System.out.println(createJson(jsonObject));
os.flush();
os.close();
int responseCode = connection.getResponseCode();
} catch (Exception e){
System.out.println("Unable to make post request!");
System.out.println(e.getCause());
System.out.println(e.getStackTrace());
System.out.println(URL);
}
}
public static String readFromConnection(HttpURLConnection connection) throws IOException {
StringBuilder content;
BufferedReader input = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
content = new StringBuilder();
while ((line = input.readLine()) != null) {
content.append(line);
}
return content.toString();
}
public static String createJson(JSONObject jsonObject){
StringBuilder tempString = new StringBuilder();
tempString.append("{");
int count = 0;
for(String key : jsonObject.keySet()){
if(count!=0)
tempString.append(",");
tempString.append("\"");
tempString.append(key);
tempString.append("\"");
tempString.append(":");
String temp = jsonObject.get(key).toString();
temp = temp.substring(1);
temp = temp.substring(0,temp.length()-2);
tempString.append(temp);
tempString.append("\"");
count++;
}
tempString.delete(tempString.length()-1,tempString.length()-1);
tempString.append("}");
return tempString.toString();
}
}
我也尝试过使用 AsyncTask 但我无法让它工作。
public class LoginAsync extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
String tempurl = "https://radiant-bayou-97811.herokuapp.com" + "/api/user/login/" + "user" + "/" + "test";
JSONObject jsonObject = getRequest(tempurl);
System.out.println(jsonObject);
System.out.println(tempurl);
if (jsonObject.has("login")) {
try {
if (jsonObject.get("login").equals("true"))
return 1L;
else
return 0L;
} catch (JSONException e) {
e.printStackTrace();
}
}
else
return 0L;
return 0L;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(String result) {
System.out.println("something");
}
然后我只是用一些随机的 url 调用 LoginAsync。我不明白我做错了什么。
解决方案
在...上运行良好...无论如何...但不是... Android ...
如果错误仅在 Android 设备(或 Android Studio IDE 中的模拟设备)上运行代码时发生,则表明您的 android 权限设置可能丢失了某些内容...
你添加<user-permission android:name="android.permission.INTERNET" />
到你的 AndroidManifest.xml 了吗?
推荐阅读
- flutterwebviewplugin - Flutter Webview 隐藏除一个 Div/Class 之外的所有内容
- php - 合并和汇总对象数组中的某些项目属性
- docker - 如何访问卷的主机目录名称?
- vue.js - 通过 href 或 nuxt-link 方法生成的重定向链接
- java - 第二个源文件夹中的类的 Eclipse 启动配置失败
- ansible - 从ansible剧本中提取json
- php - 使用 PHP SOAP 客户端提供 Docker 容器
- java - LibGdx - 如何在保持纵横比的同时调整游戏窗口的大小?
- python - libjpeg.9.dylib 版本更新
- swift - 用用户选择的照片替换集合视图中的默认图像 - swift