向Android Studio(Java)中的API发送请求时出现问题
我在连接到API时遇到问题。我的请求似乎还可以,但我的身份验证似乎不正确。有人能帮我吗 url和API Put请求是正确的,我使用mozilla HTTP请求程序对其进行了测试。但我没有成功。我得到HTTP 403作为响应代码,所以我认为我的身份验证有问题向Android Studio(Java)中的API发送请求时出现问题,java,android,api,request,put,Java,Android,Api,Request,Put,我在连接到API时遇到问题。我的请求似乎还可以,但我的身份验证似乎不正确。有人能帮我吗 url和API Put请求是正确的,我使用mozilla HTTP请求程序对其进行了测试。但我没有成功。我得到HTTP 403作为响应代码,所以我认为我的身份验证有问题 public String doWork(String pMail, String pPassword, String pNickname) { String output = ""; try {
public String doWork(String pMail, String pPassword, String pNickname) {
String output = "";
try {
//authentification header?
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(
"admin@domain.com", "password".toCharArray());
}
});
//Test: These parameters need to be sent from the GUI
pMail = "name@domain.com";
pPassword = "Testpassword";
pNickname = "Testuser";
String password = "password";
String username = "admin@domain.com";
//new try for authentification
String authstring = username + ":" + password;
byte[] authEncBytes = Base64.encode(authstring.getBytes(), 0);
URL url = new URL("https://domain/API");
//create https connection
HttpsURLConnection httpsCon = null;
httpsCon = (HttpsURLConnection) url.openConnection();
httpsCon.setRequestProperty("Authorization", "Basic " + authEncBytes);
httpsCon.setRequestMethod("PUT");
httpsCon.setRequestProperty("Content-Type", "application/json");
httpsCon.setRequestProperty("Accept-Language", "de");
OutputStreamWriter out = new OutputStreamWriter(
httpsCon.getOutputStream());
out.write("/Users/" + pMail + "/" + pPassword + "/" + pNickname);
out.close();
httpsCon.getInputStream();
} catch (Exception e) {
output = e.toString();
System.out.println(output);
}
return output;
}
我对Android Studio和必要的java编程非常陌生。所以,如果有人能给我一个提示,那就太好了:-)
这是我的代码(它已经在一个异步任务中,我没有得到NetworkInMainThreadException)
我还得到“方法不支持请求体:PUT”,但我认为这是因为身份验证
public String doWork(String pMail, String pPassword, String pNickname) {
String output = "";
try {
//authentification header?
Authenticator.setDefault(new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(
"admin@domain.com", "password".toCharArray());
}
});
//Test: These parameters need to be sent from the GUI
pMail = "name@domain.com";
pPassword = "Testpassword";
pNickname = "Testuser";
String password = "password";
String username = "admin@domain.com";
//new try for authentification
String authstring = username + ":" + password;
byte[] authEncBytes = Base64.encode(authstring.getBytes(), 0);
URL url = new URL("https://domain/API");
//create https connection
HttpsURLConnection httpsCon = null;
httpsCon = (HttpsURLConnection) url.openConnection();
httpsCon.setRequestProperty("Authorization", "Basic " + authEncBytes);
httpsCon.setRequestMethod("PUT");
httpsCon.setRequestProperty("Content-Type", "application/json");
httpsCon.setRequestProperty("Accept-Language", "de");
OutputStreamWriter out = new OutputStreamWriter(
httpsCon.getOutputStream());
out.write("/Users/" + pMail + "/" + pPassword + "/" + pNickname);
out.close();
httpsCon.getInputStream();
} catch (Exception e) {
output = e.toString();
System.out.println(output);
}
return output;
}
我也有类似的问题。这段代码对我有用。这是AsyncTask类中的doInBackground方法
protected String doInBackground(Void... urls) {
try {
URL url = new URL ("https://url.com/systems.json");
String userPassword = "blah" + ":" + "blah";
byte[] encodingBytes = Base64.encodeBase64(userPassword.getBytes());
String encoding = new String(encodingBytes);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Authorization", "Basic " + encoding); //basic http authetication
connection.connect();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = in.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
in.close();
return stringBuilder.toString();
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
在onPostExecute中,im将字符串作为参数,这是这段代码获得的提要。希望这有帮助
编辑:实际上,您的问题似乎是试图在UI线程中运行doWork方法。将代码从doWork方法移动到AsyncTask doInBackground方法,将不再引发异常。顺便说一句,使用一些库来执行API请求,而不是自己编写。我使用改型,但可能还有其他一些好的库。谢谢,我用截击来完成我的任务,现在我的Put、Post和Delete工作。我只剩下一个问题:如何将输出作为JSon对象 我的第一个想法是将此方法从void更改为任何数据类型(如String、Map或其他任何类型),并在末尾添加“return”。 我的第二个想法是直接在方法中处理JSon 谁能给我一个提示吗 public void getUserGroups(字符串pUserID) { 字符串getCommand=“”; getCommand=API_URL+“组/组/”+pUserID
StringRequest stringRequest = new StringRequest(Request.Method.GET, getCommand, new Response.Listener<String>()
{
@Override
public void onResponse(String response) {
// Do i get my output here? ################################
// #########################################################
//here we have to check the response code
if(response.equalsIgnoreCase(""))
{
//success
}
else
{
//error-code
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//You can handle error here if you want
}
}){
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> headers = new HashMap<>();
String credentials = KEY_EMAIL + ":" + KEY_PASSWORD;
String encodedCredentials = Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
headers.put("Authorization", "Basic " + encodedCredentials);
//returning parameter
return headers;
}
};
//Adding the string request to the queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
StringRequest-StringRequest=new-StringRequest(Request.Method.GET,getCommand,new-Response.Listener())
{
@凌驾
公共void onResponse(字符串响应){
//我在这里得到我的输出吗################################
// #########################################################
//这里我们必须检查响应代码
if(response.equalsIgnoreCase(“”)
{
//成功
}
其他的
{
//错误代码
}
}
},
新的Response.ErrorListener(){
@凌驾
公共无效onErrorResponse(截击错误){
//如果需要,可以在此处处理错误
}
}){
@凌驾
公共映射getHeaders()引发AuthFailureError{
Map headers=newhashmap();
字符串凭据=密钥\电子邮件+“:”+密钥\密码;
字符串encodedCredentials=Base64.encodeToString(credentials.getBytes(),Base64.NO_WRAP);
标题。put(“授权”、“基本”+encodedCredentials);
//返回参数
返回标题;
}
};
//将字符串请求添加到队列
RequestQueue RequestQueue=Volley.newRequestQueue(this);
添加(stringRequest);
}