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() + "");
Related
I am using http request. I have two image to call api. Image are base64encoding..but in postman it is working fine. It is not working in my java code..it shows bellow error
response = HTTP/1.1 400 Bad Request [Server: nginx/1.14.0 (Ubuntu), Date: Fri, 13 Nov 2020 09:24:20 GMT, Content-Type: application/json; charset=utf-8, Content-Length: 3866, Connection: keep-alive, X-Powered-By: Express, Access-Control-Allow-Origin: *, Access-Control-Expose-Headers: Origin, X-Requested-With, Content-Type, Accept, x-auth-token, x-login-token, x-verification-token, ETag: W/"f1a-xqn4nWVQUqRNj8g2mv5av6fbTrg"]
statusCode = 400
Postman header image
Postman body
I have used bellow code..
byte[] photo1=null;
byte[] photo2=null;
String base64encodedString = Base64.getEncoder().encodeToString(photo1);
String base64encodedString2 = Base64.getEncoder().encodeToString(photo2);
try {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("url");
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("photo", base64encodedString);
jsonObject.put("nidFront", base64encodedString2);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("jsonObject = " + jsonObject);
StringEntity params = new StringEntity(String.valueOf(jsonObject));
httppost.addHeader("content-type", "application/json");
httppost.setHeader("x-auth-token", token);
httppost.setEntity(params);
HttpResponse response = httpclient.execute(httppost);
int statusCode = response.getStatusLine().getStatusCode();
System.out.println("statusCode = " + statusCode);
Please help me what is wrong in code
static HttpClient httpclient = new DefaultHttpClient();
static HttpPost httppost = new HttpPost("http://servername:6405/biprws/logon/long");
public static void main(String[] args) throws ClientProtocolException, IOException {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("userName", "Administrator"));
postParameters.add(new BasicNameValuePair("password", "test"));
postParameters.add(new BasicNameValuePair("auth", "secEnterprise"));
httppost.setEntity(new UrlEncodedFormEntity(postParameters));
httppost.addHeader("accept", "application/json");
httppost.addHeader("Content-Type", "application/json");
HttpResponse response = httpclient.execute(httppost);
Header s = response.getFirstHeader("logontoken");
String s1 = s.getValue();
System.out.println(s1);// null pointer exception here
}
Running the code above i am not able to add request body to the POST request. How can i achieve this?
Alternative method i followed:
HttpClient client1 = new DefaultHttpClient();
HttpPost post = new HttpPost("http://servername:6405/biprws/logon/long");
String json = "{\"UserName\":\"Administrator\",\"Password\":\"test\",\"Auth\":\"secEnterprise\"}";
StringEntity entity = new StringEntity(json,"UTF-8");
entity.setContentType("application/json");
post.setEntity(entity);
System.out.println(entity);
post.setHeader("Accept", "application/json");
HttpResponse response = client1.execute(post);
BufferedReader rd1 = new BufferedReader(
new InputStreamReader(response.getEntity().getContent()));
String result1 = null;
String line1 = "";
result1 = rd1.readLine();
System.out.println(result1);
Still i am not able to make request.
You are successfully receiving a response which does not contain the "logontoken" header. Very possibly because the response is not an HTTP 200 OK response. Why? We don't know, it all depends on the protocol that your server implements on top of HTTP.
That having been said, the use of both httppost.setEntity(new UrlEncodedFromEntity(postParameters)) and httppost.addHeder("Content-Type", "application/json") does not look right to me. A URL-encoded form entity is not of json content type. So, either convert your post parameters to json, or lose the content-type header.
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 am currently using HttpGet(apache) method to make a request to a web service.
When I was calling the server it was giving me this error:
"The difference between the request time and the server time is too large"
Then I came to know that the server needs to have the request in GMT so I did add accordingly an header (addHeader) to do the same. But still I have the same issue.
Any thoughts/ideas?
some code:
final String url = "ip address";
final HttpGet request = new HttpGet(url);
final ArrayList<NameValuePair> nameValues = new ArrayList<NameValuePair>();
nameValues.add(new BasicNameValuePair("Authorization", "XXXX"));
nameValues.add(new BasicNameValuePair("date", "Fri, 19 Aug 2011 22:39:13 GMT"));
for (final NameValuePair h : nameValues)
{
request.addHeader(h.getName(), h.getValue());
}
final HttpClient client = new DefaultHttpClient();
HttpResponse httpResponse;
try
{
httpResponse = client.execute(request);
responseCode = httpResponse.getStatusLine().getStatusCode();
message = httpResponse.getStatusLine().getReasonPhrase();
final HttpEntity entity = httpResponse.getEntity();
if (entity != null)
{
final InputStream instream = entity.getContent();
response = convertStreamToString(instream);
instream.close();
}
}
catch (final Exception e)
{
}
I was able to get it resolved.
I found out that the server has being set to GMT while I was calling with CST.
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!