HTTP POST method returning status code 404 - java

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

Related

http post request return 400

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.

how to call web service in java using post method

public static String[] Webcall(String emailID) {
try {
URL url = new URL(AppConfig.URL + emailID);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept", "application/json");
conn.setRequestProperty("Authorization", "application/json");
conn.setRequestProperty("userEmailId", emailID);
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
org.json.JSONObject _jsonObject = new org.json.JSONObject(output);
org.json.JSONArray _jArray = _jsonObject.getJSONArray("manager");
String[] str = new String[_jArray.length()];
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
This is my code I am trying to call web service and get data.
But when I hit web service then I am getting below exception
Failed : HTTP error code : 404
Please suggest me where am doing wrong try to give solution for this .
The first thing is check url is it working on computer using postman or restclient and if it is working fine then tried to post using below code, this code is for posting data in json format using HttpPost you can use retrofit lib as Milad suggested.
public static String POST(String url, String email)
{
InputStream inputStream = null;
String result = "";
try {
// 1. create HttpClient
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(url);
String json = "";
// 3. build jsonObject
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("email", email);
// 4. convert JSONObject to JSON to String
json = jsonObject.toString();
// 5. set json to StringEntity
StringEntity se = new StringEntity(json);
// 6. set httpPost Entity
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. receive response as inputStream
inputStream = httpResponse.getEntity().getContent();
// 10. convert inputstream to string
if(inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
// 11. return result
return result;
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException{
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line = "";
String result = "";
while((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
I think u should try to re-check URL that you send request to.
follow the output error, code 404 that mean the URL is broken or dead link.
You can do the same by using jersy-client and jersy core.Here is the code snippet
private static void generateXML(String xmlName, String requestXML, String url)
{
try
{
Client client = Client.create();
WebResource webResource = client
.resource(url);
ClientResponse response = (ClientResponse)webResource.accept(new String[] { "application/xml" }).post(ClientResponse.class, requestXML);
if (response.getStatus() != 200) {
throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
}
String output = (String)response.getEntity(String.class);
PrintWriter writer = new PrintWriter(xmlName, "UTF-8");
writer.println(output);
writer.close();
}
catch (Exception e) {
try {
throw new CustomException("Rest-Client May Be Not Working From Your System");
} catch (CustomException e1) {
System.exit(1);
}
}
}
Call this method from your code with varibales.

apache httpcomponents.httpClient strangest error ever

we are developing an android app and my current part is to implement uploading files.
I'm using httpcore-4.2.2, httpclient-4.2.2 and httpmime-4.2.2.
My problem now is that the file will only be send with the httpclient if the URI has a really specific description... if I use another URI the post-body on the server-side is empty... and I am really not capable of understanding this issue.
My code looks as follows:
public static String getUploadLink() {
String server = Mobile4dApplication.getContext().getString(R.string.default_server_address);
String parameter = "/Files/upload";
String finalQuery = String.format("%s%s", server, parameter);
Log.d("UploadService", finalQuery );
return finalQuery;
}
private String uploadFile(String uploadURL, File uploadFile, String title, long id) throws UnsupportedEncodingException, FileNotFoundException {
MultipartEntity multipartEntity = new MultipartEntity( );
multipartEntity.addPart( "file", new FileBody( uploadFile ) );
HttpResult httpResult;
try {
httpResult = HttpCommunicator.sendPOST( uploadURL, multipartEntity );
} catch (IOException e) {
e.printStackTrace();
return null;
}
// TODO remove sysout line when it is not needed anymore
System.out.println("result: " + httpResult.getResultMessage());
return httpResult.getResultMessage();
}
public static HttpResult sendPOST(String targetURL, HttpEntity entity) throws IOException {
HttpClient httpClient = getHttpClient();
HttpParams httpParams = httpClient.getParams();
HttpConnectionParams.setConnectionTimeout(httpParams, connectionTimeoutMillis);
HttpConnectionParams.setSoTimeout(httpParams, socketTimeoutMillis);
HttpPost httppost = new HttpPost(targetURL);
httppost.setEntity(entity);
HttpResponse response = httpClient.execute(httppost);
String result = "";
if (response != null && response.getEntity() != null) {
result = EntityUtils.toString(response.getEntity(), UTF_8_ENCODING);
}
return new HttpResult(result, response.getStatusLine().getStatusCode());
}
if I use the URI serveraddress/Files/upload everything looks fine on the server side. But if I change the part with "Files/upload" even in the slightest the whole post-body turns out to be empty when it reaches our server...
I am completely out of ideas... I really hope that someone can help...

HTTPResponse's string from Play is empty

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.

How to send simple http post request with post parameters in java

I need a simple code example of sending http post request with post parameters that I get from form inputs.
I have found Apache HTTPClient, it has very reach API and lots of sophisticated examples, but I couldn't find a simple example of sending http post request with input parameters and getting text response.
Update: I'm interested in Apache HTTPClient v.4.x, as 3.x is deprecated.
Here's the sample code for Http POST, using Apache HTTPClient API.
import java.io.InputStream;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
public class PostExample {
public static void main(String[] args){
String url = "http://www.google.com";
InputStream in = null;
try {
HttpClient client = new HttpClient();
PostMethod method = new PostMethod(url);
//Add any parameter if u want to send it with Post req.
method.addParameter("p", "apple");
int statusCode = client.executeMethod(method);
if (statusCode != -1) {
in = method.getResponseBodyAsStream();
}
System.out.println(in);
} catch (Exception e) {
e.printStackTrace();
}
}
}
I pulled this code from an Android project by Andrew Gertig that I have used in my application. It allows you to do an HTTPost. If I had time, I would create an POJO example, but hopefully, you can dissect the code and find what you need.
Arshak
https://github.com/AndrewGertig/RubyDroid/blob/master/src/com/gertig/rubydroid/AddEventView.java
private void postEvents()
{
DefaultHttpClient client = new DefaultHttpClient();
/** FOR LOCAL DEV HttpPost post = new HttpPost("http://192.168.0.186:3000/events"); //works with and without "/create" on the end */
HttpPost post = new HttpPost("http://cold-leaf-59.heroku.com/myevents");
JSONObject holder = new JSONObject();
JSONObject eventObj = new JSONObject();
Double budgetVal = 99.9;
budgetVal = Double.parseDouble(eventBudgetView.getText().toString());
try {
eventObj.put("budget", budgetVal);
eventObj.put("name", eventNameView.getText().toString());
holder.put("myevent", eventObj);
Log.e("Event JSON", "Event JSON = "+ holder.toString());
StringEntity se = new StringEntity(holder.toString());
post.setEntity(se);
post.setHeader("Content-Type","application/json");
} catch (UnsupportedEncodingException e) {
Log.e("Error",""+e);
e.printStackTrace();
} catch (JSONException js) {
js.printStackTrace();
}
HttpResponse response = null;
try {
response = client.execute(post);
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.e("ClientProtocol",""+e);
} catch (IOException e) {
e.printStackTrace();
Log.e("IO",""+e);
}
HttpEntity entity = response.getEntity();
if (entity != null) {
try {
entity.consumeContent();
} catch (IOException e) {
Log.e("IO E",""+e);
e.printStackTrace();
}
}
Toast.makeText(this, "Your post was successfully uploaded", Toast.LENGTH_LONG).show();
}
HTTP POST request example using Apache HttpClient v.4.x
HttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody("param1", param1Value, ContentType.TEXT_PLAIN);
builder.addTextBody("param2", param2Value, ContentType.TEXT_PLAIN);
HttpEntity multipart = builder.build();
httpPost.setEntity(multipart);
HttpResponse response = httpClient.execute(httpMethod);
http://httpunit.sourceforge.net/doc/cookbook.html
use PostMethodWebRequest and setParameter method
shows a very simple exapmle where you do post from Html page, servlet processes it and sends a text response..
http://java.sun.com/developer/onlineTraining/Programming/BasicJava1/servlet.html

Categories

Resources