我正在使用HTTP post方法调用Gitlab API,作为回报,它给了我400个响应代码。
我已经用邮递员测试了gitlab api,并提供了适当的标头和内容主体作为JSON。 它工作正常,并且。 (我使用gitlab create分支api)
我已经使用eclipse调试了应用程序,并且有一些特定的行给了我null
我正在使用apache http客户端4.5.5来处理http请求。
这是我创建分支的第一个方法
public HttpResponse createBranch(String projectId, String branchName, String ref) {
// url is ok, i debugged it
String url = this.API_BASE_URL + projectId + "/repository/branches";
//branchName = "uifix branch";
//ref = "master";
JSONObject obj = new JSONObject();
try {
obj.put("branch", branchName);
obj.put("ref", ref);
} catch (JSONException e) {
e.printStackTrace();
}
Map<String, String> headerParams = new HashMap<String, String>();
headerParams.put("Private-Token", PAT);
headerParams.put("Content-Type", "application/json; utf-8");
headerParams.put("Accept", "application/json");
return HttpUtility.httpPostForResourceCreation(url, headerParams, obj.toString());
}
然后将调用httputlity类中的以下方法。
public static HttpResponse httpPostForResourceCreation(String url, Map<String, String> headerParam, String body) {
HttpPost request = new HttpPost(url);
StringEntity params = new StringEntity(body, ContentType.APPLICATION_JSON);
for (Map.Entry<String, String> entry : headerParam.entrySet()) {
request.setHeader(entry.getKey(), entry.getValue());
}
request.setEntity(params); // I think problem is here. when I debugged it , it shows null.
return execute(request);
}
然后将调用最后一个方法
private static HttpResponse execute(HttpRequestBase request) {
HttpClient httpClient = HttpUtility.buildHttpClient();
HttpResponse response = null;
try {
response = httpClient.execute(request);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if(response.getStatusLine().getStatusCode() == 201) {
System.out.println("resource successfully created: " + 201);
} else {
System.out.println("resource creation failed: " + response.getStatusLine().getStatusCode());
}
return response;
}
预期结果应为“资源成功创建:+ 201” 而不是得到“资源创建失败:400”
那么,我在这里想念的是什么?任何帮助将不胜感激。