![](/img/trans.png)
[英]How to make HTTP Request with authentication info from WebView in Android?
[英]How to make a http request from Android?
我正在嘗試制作一個移動應用程序,我目前正在創建 api 用於與服務器通信。 我的代碼在正常的 maven 項目上工作正常,但是當我將它添加到我的 android 工作室項目時,當我嘗試從連接輸入 stream 讀取時出現錯誤。
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 中?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.