I'm using HTTP post method to call Gitlab API which in return it gives me 400 response code.
I have tested the gitlab api with postman with providing propers headers and content body as JSON.
it worked fine and. ( I use gitlab create branch api )
I have debugged the application using eclipse and , there is some specific line which gave me null
I'm using apache http client 4.5.5 to handle http requests.
this is my first method to create a branch
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());
}
then will call the following method which is in httputlity class.
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);
}
then will call the last method
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;
}
expected result should be "resource successfully created: + 201"
instead of I'm getting "resource creation failed: 400"
here I attached my request object content
so, what I'm missing here ? Any help would be appreciated.
Related
I have an object that I want to parse to a JSON string. When I want to read it out, it says it can't parse it back to an object (i think). This is the error:
As you can see at the top of the console, the JSON object is set properly with the right brackets. What I understand from the JSONSyntaxException is that it doesn't recognize it as a JSON object. I've copied this code from my school and in a different project it does work. I don't know why it doesn't work in my Maven project.
EDIT
This is the code for RESTcontroller.java.
public PlayerDTO addPlayer(String name, String password) {
PlayerDTO playerRequest = new PlayerDTO(NOTDEFINED, name, password);
String queryPost = "/player";
PlayerResponse response = executeQueryPost(playerRequest, queryPost);
return response.getPlayers().get(0);
}
private PlayerResponse executeQueryPost(PlayerDTO playerRequest, String queryPost) {
final String query = url + queryPost;
log.info("[Query POST] : " + query);
HttpPost httpPost = new HttpPost(query);
httpPost.addHeader("content-type", "application/json");
StringEntity params;
try{
params = new StringEntity(gson.toJson(playerRequest));
System.out.println(gson.toJson(playerRequest));
httpPost.setEntity(params);
} catch (UnsupportedEncodingException e) {
Logger.getLogger(SeaBattleGame.class.getName()).log(Level.SEVERE, null, e);
}
return executeHttpUriRequest(httpPost);
}
private PlayerResponse executeHttpUriRequest(HttpUriRequest httpUriRequest) {
// Execute the HttpUriRequest
try (CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(httpUriRequest)) {
log.info("[Status Line] : " + response.getStatusLine());
HttpEntity entity = response.getEntity();
final String entityString = EntityUtils.toString(entity);
log.info("[Entity] : " + entityString);
return gson.fromJson(entityString, PlayerResponse.class);
} catch (IOException e) {
log.info("IOException : " + e.toString());
PlayerResponse playerResponse = new PlayerResponse();
playerResponse.setSuccess(false);
return playerResponse;
} catch (JsonSyntaxException e) {
log.info("JsonSyntaxException : " + e.toString());
PlayerResponse playerResponse = new PlayerResponse();
playerResponse.setSuccess(false);
return playerResponse;
}
}
Keep in mind that the code gave me this code and it does work in their project!
It would seem to me that your request is failing with this error: Problem accessing /seabattle/player Reason: request failed. It's not very discriptive, but it's something.
Your code is then failing with a NullPointerException, I'm guessing response.getPlayers() is returning a null.
You should really try and send a similar JSON to this endpoint from a curl command or via Postman app and see if it works. Or if you can, see the webserver logs to find out what the actual problem is.
EDIT: You should really also check the response status before trying to parse it. This will get rid of the NullPointerException and will make your code better in general.
A couple of things to fix the issue:
In the method executeQueryPost you have to add the following headers for the request:
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
And the code should look like the following:
private PlayerResponse executeQueryPost(PlayerDTO playerRequest, String queryPost) {
final String query = url + queryPost;
log.info("[Query POST] : " + query);
HttpPost httpPost = new HttpPost(query);
httpPost.addHeader("content-type", "application/json");
StringEntity params;
try{
params = new StringEntity(gson.toJson(playerRequest));
System.out.println(gson.toJson(playerRequest));
httpPost.setEntity(params);
// Need to add the following headers
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
} catch (UnsupportedEncodingException e) {
Logger.getLogger(SeaBattleGame.class.getName()).log(Level.SEVERE, null, e);
}
return executeHttpUriRequest(httpPost);
}
In case the the code continue failing is because it can't create the new player. You must handle the exception in addPlayer() method. Before the return check if the object returned by executeQueryPost is not null.
Update:
The code may be failing just because the service in: http://localhost:8090 isn't running that's why it getting 500 as response.
I am trying to validate a login using the below code. My challenge is to how get a response of 200 status code and if yes display the welcome screen. This is my code attempt but it has no status to confirm is the post is successful thereafter take the next action.
public void executeLoginValidation() {
Map<String, String> comment = new HashMap<String, String>();
comment.put("email", loginActivityEmail.getText().toString());
comment.put("password", loginActivityPassword.getText().toString());
String json = new GsonBuilder().create().toJson(comment, Map.class);
makeRequest("http://localhost:88/API/web/app_dev.php/validatelogin/", json);
}
public static HttpResponse makeRequest(String uri, String json) {
try {
HttpPost httpPost = new HttpPost(uri);
httpPost.setEntity(new StringEntity(json));
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
return new DefaultHttpClient().execute(httpPost);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
Please how can I modify the above form post code to return a status code and thereafter take the necessary step fron login screen
As the other said before me, try getting the status code from the HttpResponse:
public void executeLoginValidation() {
Map<String, String> comment = new HashMap<String, String>();
comment.put("email", loginActivityEmail.getText().toString());
comment.put("password", loginActivityPassword.getText().toString());
String json = new GsonBuilder().create().toJson(comment, Map.class);
HttpResponse response = makeRequest("http://localhost:88/API/web/app_dev.php/validatelogin/",json);
int statusCode = response.getStatusLine().getStatusCode();
if(statusCode == 200){
showSplashScreen();
}else{
//ErrorHandling
}
}
I am trying to post JSON data to my API. But after execution I'm getting the following result:
{"name":"Corporate","addr":"Unknown","area":"Unknown","cityId":10,"phone":"--","fax":"--","wooqStoreId":1}]
Response 2 >>{"message":"Blank String","result":"Error","resultCode":"RESULT_CODE_002"}
true
The first 2 lines show my JSON string and
response 2 is the message I'm getting. It should be a successful message as I'm getting status code 200.
public static boolean pushtoAPI(String url, String jsonObject) {
DefaultHttpClient client = new DefaultHttpClient();
HttpPost request = null;
HttpResponse response = null;
String postUrl = getHostUrl() + url;
try {
request = new HttpPost(postUrl);
StringEntity postingString = new StringEntity(jsonObject.toString());
postingString.setContentType("application/json;charset=UTF-8");
postingString.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
"application/json;charset=UTF-8"));
request.setEntity(postingString);
request.setHeader("Content-type", "application/json");
String custom_cookie = ConstantUtil.authCookie(ConstantUtil.getLoginJsessionId());
request.setHeader("Cookie", custom_cookie);
response = client.execute(request);
System.out.println("Response 2 >>" + EntityUtils.toString(response.getEntity()));
if (response.getStatusLine().getStatusCode() == 200) {
System.out.println("true");
return true;
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
} finally {
request.abort();
}
return false;
}
It looks like its a server side code issue.
Can you show where you are creating this string?
"message":"Blank
String","result":"Error","resultCode":"RESULT_CODE_002"
When I execute an API through following method, I always get 404 as response code.
private void execute() throws IllegalStateException, IOException, NoSuchAlgorithmException {
Map<String, String> comment = new HashMap<String, String>();
comment.put("accounts-groups", "customers/enterprise");
comment.put("companyType", "customer");
comment.put("companyName", "Test");
String json = new GsonBuilder().create().toJson(comment, Map.class);
Log.i(TAG, "json : "+json);
HttpResponse response = makeRequest(URL, json);
/*Checking response */
if(response != null) {
InputStream inputStream = response.getEntity().getContent(); //Get the data in the entity
int statusCode = response.getStatusLine().getStatusCode();
Log.i(TAG, "statusCode : "+statusCode);
String result;
// convert inputstream to string
if(inputStream != null)
result = convertStreamToString(inputStream);
else
result = "Did not work!";
Log.i(TAG, "result : "+result);
}
}
private HttpResponse makeRequest(String uri, String json) throws NoSuchAlgorithmException {
Log.i(TAG, "uri : "+uri);
try {
HttpPost httpPost = new HttpPost(uri);
httpPost.setEntity(new StringEntity(json, HTTP.UTF_8));
long timestamp = System.currentTimeMillis();
String signatureKey = PRIVATE_KEY + timestamp;
byte[] bytesOfMessage = signatureKey.getBytes(HTTP.UTF_8);
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] thedigest = md.digest(bytesOfMessage);
char[] signature = Hex.encodeHex(thedigest);
String finalSignature = String.valueOf(signature);
Log.i(TAG, "finalSignature : "+finalSignature);
httpPost.setHeader("Timestamp", ""+timestamp);
httpPost.setHeader("Api_token", API_TOKEN);
httpPost.setHeader("Signature" , finalSignature);
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader(HTTP.CONTENT_TYPE, "application/json");
return new DefaultHttpClient().execute(httpPost);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
I am not getting where am I going wrong. Can anybody please help me out?
from wiki:
The 404 or Not Found error message is a HTTP standard response code
indicating that the client was able to communicate with the server,
but the server could not find what was requested.
so, your code is OK, but server cannot find resource you are looking for. Double check if your url is correct.
how to pass request through fiddler proxy for debugging purposes:
HttpParams params = new BasicHttpParams();
// ....
HttpHost proxy = new HttpHost("192.168.1.12", 8888); // IP to your PC with fiddler proxy
params.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
// use params as a second parameter to: following constructor:
// public DefaultHttpClient (ClientConnectionManager conman, HttpParams params)
I was getting 404 for POST requests because mod_headers module of Apache 2 server was not enabled. If that happens you can enable it with:
sudo a2enmod headers
and then restart apache:
sudo service apache2 restart
I am using Play and Faye on my Server. Play is used for API calls, while Faye is used for communication with the clients.
So, I have this method in the server:
public static Result broadcast(String channel, String message)
{
try
{
FayeClient faye = new FayeClient("localhost");
int code = faye.send(channel, message);
// print the code (prints 200).
return ok("Hello"); <------------ This is what we care about.
}
catch(Exception e)
{
return ok("false");
}
}
this is the code on the client, which is an android phone.
(it's the HTTP post method, which sends something to the server and gets a response back
The problem is, I can't print the message of the response.
public static String post(String url, List<BasicNameValuePair> params)
{
HttpClient httpclient = new DefaultHttpClient();
String result = "";
// Prepare a request object
HttpPost httpPost;
httpPost = new HttpPost(url);
httpPost.setHeader("Content-type", "application/json");
httpPost.setHeader("Accept", "application/json");
JSONObject obj = new JSONObject();
try
{
for (NameValuePair pair : params)
obj.put(pair.getName(), pair.getValue());
}
catch (JSONException e)
{
return e.getMessage();
}
// Add your data
try
{
httpPost.setEntity(new StringEntity(obj.toString(), "UTF-8"));
}
catch (UnsupportedEncodingException e)
{
return e.getMessage();
}
HttpResponse httpResponse;
try
{
httpResponse = httpclient.execute(httpPost);
// Get hold of the response entity
HttpEntity entity = httpResponse.getEntity();
String str = EntityUtils.toString(entity);
Log.e("RestClient", "result = \"" + str + "\""); // hello should be printed here??
}
catch(Exception e)
{
// ...
}
The problem is that in logcat, what is printed is [result = ""]. Am I doing something wrong?
Thank you.
Use a tool such as Fiddler and see what the HTTP response contains.