java如何从Android发出http请求?
我正在尝试制作一个移动应用程序,目前正在创建用于与服务器通信的api。我的代码在普通的maven项目上运行良好,但当我将其添加到安卓 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。我不明白我做错了什么
# 1 楼答案
如果错误只发生在Android设备(或Android Studio IDE中的模拟设备)上运行代码时,这暗示您的Android权限设置可能丢失了某些内容
您是否已将
<user-permission android:name="android.permission.INTERNET" />
添加到您的AndroidManifest中。xml