我在连接API时遇到问题。我的请求似乎没问题,但似乎我的身份验证不正确。有人能帮助我吗?
网址和API-Put-request是正确的,我使用mozilla HTTP-Requester对其进行了测试。但我没有成功。我得到HTTP 403作为响应代码,所以我认为我的身份验证有问题。
我是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;
}
答案 0 :(得分:0)
有类似的问题。这段代码对我有用。这是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中,我将一个字符串作为参数,这是这个代码块得到的提要。希望这会有所帮助。
编辑:实际上你的问题似乎是你试图在UI线程中运行doWork方法。将代码从doWork方法移动到AsyncTask doInBackground方法,异常不再被抛出。
答案 1 :(得分:0)
顺便说一下,使用一些库来执行API请求,而不是自己编写。我使用Retrofit,但可能还有其他一些好的库。
答案 2 :(得分:0)
谢谢,我用Volley来完成我的任务,现在我的Put and Post和Delete工作了。我只剩下一个问题:如何将输出作为JSon-Object?
我的第一个想法是将此方法从void更改为任何数据类型(如String,Map或其他任何内容),并在末尾添加“return”。 我的第二个想法是在方法中直接处理JSon。
任何人都可以给我一个提示吗?
public void getUserGroups(String pUserID) { String getCommand =“”; getCommand = API_URL +“Groups / Group /”+ 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);
}