Trying to calling post method using main method but getting 400 Bad request. I am using below code
private static String POST_URL = "http://localhost:8080/RestApi/api/v1/getDetails";
public static void main(String[] args) {
try {
sendPost();
} catch (Exception e) {
System.out.println("Exception occurred while calling service and exception is " + e);
}
}
private static void sendPost() throws Exception {
HttpPost post = new HttpPost(POST_URL);
post.addHeader(HttpHeaders.CONTENT_TYPE, "application/json");
// add request parameter, form parameters
List<NameValuePair> urlParameters = new ArrayList<>();
urlParameters.add(new BasicNameValuePair("id", "1004906799"));
urlParameters.add(new BasicNameValuePair("identifer", "Customer"));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
try (CloseableHttpClient httpClient = HttpClients.createDefault(); CloseableHttpResponse response = httpClient.execute(post)) {
System.out.println(EntityUtils.toString(response.getEntity()));
}
}
> Response : HTTP/1.1 400 Bad Request [Connection: keep-alive,
> X-Powered-By: Undertow/1, Server: WildFly/8, Content-Length: 0, Date:
> Mon, 14 Oct 2019 09:44:34 GMT]
Try by setting the encoding. Replace post.setEntity(new UrlEncodedFormEntity(urlParameters)); line with
post.setEntity(new UrlEncodedFormEntity(urlParameters, "UTF-8"));
Haven't run it but should work.
The problem is that you post a form content rather than a JSON payload:
Replace those lines:
List<NameValuePair> urlParameters = new ArrayList<>();
urlParameters.add(new BasicNameValuePair("id", "1004906799"));
urlParameters.add(new BasicNameValuePair("identifer", "Customer"));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
with something like this:
String payload = "{\n" +
" \"id\": \"1004906799\",\n" +
" \"identifier\": \"Customer\"\n" +
"}";
post.setEntity(payload);
See the section 4. POST with JSON in this tutorial.
Related
I have a dropwizard service in whitch i implemented a post request who consumes APPLICATION_FORM_URLENCODED media type and uses #FormParam annotation
Then in my client i'm using Apache HttpClient to make a post request like this:
public void sendPost(String path, JsonObject params) throws Exception {
String url = "http://" + TS_API_HOST + ":" + TS_API_PORT + "/" + path;
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
Iterator<String> keys = params.keySet().iterator();
while(keys.hasNext()){
String currentKey = keys.next();
nvps.add(new BasicNameValuePair(currentKey, params.get(currentKey).toString()));
}
System.out.println(nvps.toString());
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
CloseableHttpResponse response = httpClient.execute(httpPost);
try {
System.out.println(response.getStatusLine());
HttpEntity entity2 = response.getEntity();
// do something useful with the response body
// and ensure it is fully consumed
EntityUtils.consume(entity2);
} finally {
response.close();
}
}
The url and params I'm passing are correct but i keep getting 400 bad request as a response.
In Postman it works very well...
Im trying to post to a REST API json object but i keep getting responce 404 but the url is working fine. Can anyone tell me why is this happeninig?
Here is my code:
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
HttpPost request = new HttpPost(
"http://grpsvil-webservice.si2001.it/RestChannelApp.svc/CheckCoupon");
// request.setHeader("Accept", "application/json");
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
try {
// Build JSON string
JSONStringer vehicle = new JSONStringer()
.object()
.key("CouponVerificationCode")
.value("adf")
.key("ApiKey")
.value("adfadf123")
.key("Token")
.value("fgsg342==")
.endObject();
Log.v("--", vehicle.toString());
StringEntity entity = new StringEntity(vehicle.toString());
request.setEntity(entity);
// Send request to WCF service
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
int resCode = response.getStatusLine().getStatusCode();
Log.v("--", response.getStatusLine().getStatusCode() + "");
if (resCode == 200) {
Toast.makeText(getApplicationContext(),
response.getStatusLine().getStatusCode() + "",
Toast.LENGTH_LONG).show();
BufferedReader in = new BufferedReader(
new InputStreamReader(response.getEntity()
.getContent()));
String line = "";
StringBuffer returnFromServer = new StringBuffer();
while ((line = in.readLine()) != null) {
returnFromServer.append(line);
}
// Toast what we got from server
Log.v("--", "!## " + returnFromServer.toString());
if (entity != null) {
entity.consumeContent();
}
}
} catch (Exception e) {
// TODO: handle exception
}
Intent i = new Intent(Splash.this, Login.class);
startActivity(i);
finish();
return null;
}
Endpoint not found.
Probably you write wrong methode url for this api
If you get all the WSDL from http://grpsvil-webservice.si2001.it/RestChannelApp.svc?WSDL you can see all the operations that you have defined.
CheckCoupon is not there, BUT there's a CheckPromotionalCode.
Could be that one?
The URL returns 404 not found. Just because it shows some fancy error text in the browser, doesn't mean the status code is 200 OK. This is the HTTP response that I get:
Status Code: 404 Not Found
Access-Control-Allow-Headers: Content-Type
Access-Control-Allow-Methods: GET,PUT,POST,DELETE
Age: 0
Cache-Control: private
Connection: Keep-Alive
Content-Length: 1565
Content-Type: text/html; charset=UTF-8
Date: Thu, 27 Feb 2014 14:58:03 GMT
Server: Microsoft-IIS/7.5
X-AspNet-Version: 4.0.30319
access-control-allow-origin: *
x-powered-by: ASP.NET
Try sending the verification code like this
ArrayList<NameValuePair> parms = new ArrayList<NameValuePair>();
parms.add(new BasicNameValuePair("CouponVerificationCode", adf));
parms.add(new BasicNameValuePair("ApiKey", adfadf123));
parms.add(new BasicNameValuePair("Token", fgsg342==));
httppost.setEntity(new UrlEncodedFormEntity(parms));
So your overall code will be
HttpPost request = new HttpPost(
"http://grpsvil-webservice.si2001.it/RestChannelApp.svc/CheckCoupon");
// request.setHeader("Accept", "application/json");
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
try {
ArrayList<NameValuePair> parms = new ArrayList<NameValuePair>();
parms.add(new BasicNameValuePair("CouponVerificationCode", adf));
parms.add(new BasicNameValuePair("ApiKey", adfadf123));
parms.add(new BasicNameValuePair("Token", fgsg342==));
request.setEntity(new UrlEncodedFormEntity(parms));
request.setEntity(entity);
// Send request to WCF service
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
int resCode = response.getStatusLine().getStatusCode();
Log.v("--", response.getStatusLine().getStatusCode() + "");
I have the following code that executes a httpclient post request
public void upload() throws Exception{
//HTTP POST Service
try{
HttpClient httpclient = HttpClientBuilder.create().build();
URI uri = new URIBuilder()
.setScheme("http")
.setHost("www.mysite.com")
.setPath("/mypage.php")
.setParameter("Username", userID)
.setParameter("Password", password)
.build();
HttpPost httppost = new HttpPost(uri);
httpclient.execute(httppost);
BasicHttpContext localContext = new BasicHttpContext();
HttpResponse response = httpclient.execute(httppost, localContext);
HttpUriRequest currentReq = (HttpUriRequest) localContext.getAttribute(ExecutionContext.HTTP_REQUEST);
HttpHost currentHost = (HttpHost)localContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
String currentUrl = currentHost.toURI() + currentReq.getURI();
System.out.println(currentUrl);
System.out.println(response);
HttpEntity httpEntity = response.getEntity();
String str = "";
if (httpEntity != null) {
str = EntityUtils.toString(httpEntity);
System.out.println(str);
}
}catch (Exception e) {
e.printStackTrace();
}
}
which returns
HTTP/1.1 200 OK [Date: Sat, 11 Jan 2014 16:17:22 GMT, Server: Apache, Expires: Thu, 19 Nov 1981 08:52:00 GMT, Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0, Pragma: no-cache, Vary: Accept-Encoding, Keep-Alive: timeout=10, max=30, Content-Type: text/html, Via: 1.1 NDC1-B2-CE01, Connection: keep-alive]
As if everything had worked fine but my php script on the other end doesn't seem to pick up the variable.
I've tried something as simple as:
<?php
error_log($_POST["Username"]);
?>
But get an index undefined error printed
You are setting the query parameters of the URI which builds a URI your URI like http://www.mysite.com/mypage.php?Username=userId&Password=pass
You need to set the parameters of the HttpPost with NameValuePair.
HttpPost post = new HttpPost("http://www.mysite.com/mypage.php");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Username", userId));
params.add(new BasicNameValuePair("Password", pass));
post.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = post.execute(post);
Additionally, I would recommend handling authentication with an Authorization header, such as Basic authentication as well as sending credentials over HTTPS.
I have the method sendPost() which sends a post data to login to a certain site. I am able to get the response code of 302. After executing this method, I have a sendPost2() method which will work if I am successfully logged in. However, I get the response code of 200 in sendPost2(), it also tells me that I am not logged in. It seems that after executing sendPost(), the httpclient logs me out. How do you prevent it from logging out?
Here is my sendPost() but I can't give you a valid username and password:
private void sendPost() throws Exception {
String url = "http://sblive.auf.edu.ph/schoolbliz/commfile/login.jsp";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
// add header
post.setHeader("User-Agent", USER_AGENT);
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("user_id", "testusername"));
urlParameters.add(new BasicNameValuePair("password", "testpassword"));
urlParameters.add(new BasicNameValuePair("x", "47"));
urlParameters.add(new BasicNameValuePair("y", "1"));
urlParameters.add(new BasicNameValuePair("body_color", "#9FBFD0"));
urlParameters.add(new BasicNameValuePair("welcome_url", "../PARENTS_STUDENTS/main_files/login_success.htm"));
urlParameters.add(new BasicNameValuePair("login_type", "parent_student"));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(post);
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + post.getEntity());
System.out.println("Response Code : " +
response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
StringBuffer result = new StringBuffer();
String line = "";
while ((line = rd.readLine()) != null) {
result.append(line);
}
System.out.println(result.toString());
Recipe
prepare a CookieStore
set it in the HttpContext
pass the context to every HttpClient#execute() call
You need the cookie store to have a place to keep the session ID between calls.
Code
HttpClient httpClient = new DefaultHttpClient();
CookieStore cookieStore = new BasicCookieStore();
HttpContext httpContext = new BasicHttpContext();
httpContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
// ...
HttpResponse response1 = httpClient.execute(method1, httpContext);
// ...
HttpResponse response2 = httpClient.execute(method2, httpContext);
// ...
I have to do a http post request to a web-service for authenticating the user with username and password. The Web-service guy gave me following information to construct HTTP Post request.
POST /login/dologin HTTP/1.1
Host: webservice.companyname.com
Content-Type: application/x-www-form-urlencoded
Content-Length: 48
id=username&num=password&remember=on&output=xml
The XML Response that i will be getting is
<?xml version="1.0" encoding="ISO-8859-1"?>
<login>
<message><![CDATA[]]></message>
<status><![CDATA[true]]></status>
<Rlo><![CDATA[Username]]></Rlo>
<Rsc><![CDATA[9L99PK1KGKSkfMbcsxvkF0S0UoldJ0SU]]></Rsc>
<Rm><![CDATA[b59031b85bb127661105765722cd3531==AO1YjN5QDM5ITM]]></Rm>
<Rl><![CDATA[username#company.com]]></Rl>
<uid><![CDATA[3539145]]></uid>
<Rmu><![CDATA[f8e8917f7964d4cc7c4c4226f060e3ea]]></Rmu>
</login>
This is what i am doing HttpPost postRequest = new HttpPost(urlString); How do i construct the rest of the parameters?
Here's an example previously found at androidsnippets.com (the site is currently not maintained anymore).
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
So, you can add your parameters as BasicNameValuePair.
An alternative is to use (Http)URLConnection. See also Using java.net.URLConnection to fire and handle HTTP requests. This is actually the preferred method in newer Android versions (Gingerbread+). See also this blog, this developer doc and Android's HttpURLConnection javadoc.
to #BalusC answer I would add how to convert the response in a String:
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instream = entity.getContent();
String result = RestClient.convertStreamToString(instream);
Log.i("Read from server", result);
}
Here is an example of convertStramToString.
Please consider using HttpPost. Adopt from this: http://www.javaworld.com/javatips/jw-javatip34.html
URLConnection connection = new URL("http://webservice.companyname.com/login/dologin").openConnection();
// Http Method becomes POST
connection.setDoOutput(true);
// Encode according to application/x-www-form-urlencoded specification
String content =
"id=" + URLEncoder.encode ("username") +
"&num=" + URLEncoder.encode ("password") +
"&remember=" + URLEncoder.encode ("on") +
"&output=" + URLEncoder.encode ("xml");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// Try this should be the length of you content.
// it is not neccessary equal to 48.
// content.getBytes().length is not neccessarily equal to content.length() if the String contains non ASCII characters.
connection.setRequestProperty("Content-Length", content.getBytes().length);
// Write body
OutputStream output = connection.getOutputStream();
output.write(content.getBytes());
output.close();
You will need to catch the exception yourself.
I'd rather recommend you to use Volley to make GET, PUT, POST... requests.
First, add dependency in your gradle file.
compile 'com.he5ed.lib:volley:android-cts-5.1_r4'
Now, use this code snippet to make requests.
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
StringRequest postRequest = new StringRequest( com.android.volley.Request.Method.POST, mURL,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
// response
Log.d("Response", response);
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", error.toString());
}
}
) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
//add your parameters here as key-value pairs
params.put("username", username);
params.put("password", password);
return params;
}
};
queue.add(postRequest);
Try HttpClient for Java:
http://hc.apache.org/httpclient-3.x/
You can reuse the implementation I added to ACRA:
http://code.google.com/p/acra/source/browse/tags/REL-3_1_0/CrashReport/src/org/acra/HttpUtils.java?r=236
(See the doPost(Map, Url) method, working over http and https even with self signed certs)
I used the following code to send HTTP POST from my android client app to C# desktop app on my server:
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
I worked on reading the request from a C# app on my server (something like a web server little application).
I managed to read request posted data using the following code:
server = new HttpListener();
server.Prefixes.Add("http://*:50000/");
server.Start();
HttpListenerContext context = server.GetContext();
HttpListenerContext context = obj as HttpListenerContext;
HttpListenerRequest request = context.Request;
StreamReader sr = new StreamReader(request.InputStream);
string str = sr.ReadToEnd();
HTTP request POST in java does not dump the answer?
public class HttpClientExample
{
private final String USER_AGENT = "Mozilla/5.0";
public static void main(String[] args) throws Exception
{
HttpClientExample http = new HttpClientExample();
System.out.println("\nTesting 1 - Send Http POST request");
http.sendPost();
}
// HTTP POST request
private void sendPost() throws Exception {
String url = "http://www.wmtechnology.org/Consultar-RUC/index.jsp";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
// add header
post.setHeader("User-Agent", USER_AGENT);
List<NameValuePair> urlParameters = new ArrayList<>();
urlParameters.add(new BasicNameValuePair("accion", "busqueda"));
urlParameters.add(new BasicNameValuePair("modo", "1"));
urlParameters.add(new BasicNameValuePair("nruc", "10469415177"));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(post);
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + post.getEntity());
System.out.println("Response Code : " +response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(new
InputStreamReader(response.getEntity().getContent()));
StringBuilder result = new StringBuilder();
String line = "";
while ((line = rd.readLine()) != null)
{
result.append(line);
System.out.println(line);
}
}
}
This is the web: http://www.wmtechnology.org/Consultar-RUC/index.jsp,from you can consult Ruc without captcha. Your opinions are welcome!