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
Related
I need to log in ip/api/login with parameters email, password and then I can retrieve data from ip/api/async. So far i can only log in and retrieve first call. On second app is getting SocketTimeoutException
class talkToWebSite extends AsyncTask<String, Void, String> {
protected String doInBackground(String... strings) {
OkHttpClient client = new OkHttpClient();
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
client.interceptors().add(interceptor);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://ip/")
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
TraccarApi stackOverflowAPI = retrofit.create(TraccarApi.class);
Call<Login> call1 = stackOverflowAPI.postUser("admin", "admin");
try {
call1.execute();
} catch (IOException e) {
e.printStackTrace();
}
Call<Data> call = stackOverflowAPI.getData();
Response<Data> response = null;
try {
response = call.execute();
} catch (IOException e) {
e.printStackTrace();
}
return response.body().getDataset().getData_latitude() + "";
}
protected void onPostExecute(String result) {
longitiude.setText(result);
}
}
When I am running that code I receive it:
OkHttp: --> GET /api/login?email=admin&password=admin HTTP/1.1
OkHttp: --> END GET
OkHttp: <-- HTTP/1.1 200 OK (73ms)
OkHttp: Date: Sat, 28 Nov 2015 22:19:12 GMT
OkHttp: Content-Type: application/json; charset=UTF-8
OkHttp: Access-Control-Allow-Origin: *
OkHttp: Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept
OkHttp: Access-Control-Allow-Methods: GET, POST
OkHttp: Set-Cookie: JSESSIONID=1fk50j768xc0v1w7tb8inf29nc;Path=/api
OkHttp: Expires: Thu, 01 Jan 1970 00:00:00 GMT
OkHttp: Content-Length: 189
OkHttp: Server: Jetty(9.2.14.v20151106)
OkHttp: OkHttp-Selected-Protocol: http/1.1
OkHttp: OkHttp-Sent-Millis: 1448752725041
OkHttp: OkHttp-Received-Millis: 1448752725091
OkHttp: {"success":true,"data":{"name":"admin","language":"","id":1,"map":"","readonly":false,"distanceUnit":"","speedUnit":"","latitude":0.0,"longitude":0.0,"email":"admin","admin":true,"zoom":0}}
OkHttp: <-- END HTTP (189-byte body)
OkHttp: --> GET /api/async/ HTTP/1.1
OkHttp: --> END GET
Thanks in advice.
To retrieve data from post which need authorization I need add it:
String credentials = "login:password";
final String basic = "Basic " +
Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
client.interceptors().add(new Interceptor() {
#Override
public com.squareup.okhttp.Response intercept(Interceptor.Chain chain) throws IOException {
Request original = chain.request();
Request.Builder requestBuilder = original.newBuilder()
.header("Authorization", basic)
.method(original.method(), original.body());
Request request = requestBuilder.build();
return chain.proceed(request);
}
});
I am making a json + http post in java. If the http post is successful, I should have a unique identifier string return to me from the endpoint/server. So far, my post is successful but I do not know how to print to the screen this unique identifier.
Below is the output I get when I run the program;
HttpResponseProxy{HTTP/1.1 200 OK [Server: nginx/1.6.2, Date: Sat, 13 Dec 2014 09:03:41 GMT, Content-Type: application/json; charset=utf-8, Content-Length: 24, Connection: keep-alive, Access-Control-Allow-Methods: *, Access-Control-Allow-Origin: *, X-Parse-Platform: G1, X-Runtime: 0.166030] ResponseEntityProxy{[Content-Type: application/json; charset=utf-8,Content-Length: 24,Chunked: false]}}
How do I print the return object to screen?
EDIT:
Here is my code;
//import libraries
public class XXXXXXXX {
public static void main(String[] args ) throws IOException {
// TODO Auto-generated method stub
Registration ifeanyi = new Registration();
String endPoint = "http://xxxxxxxxxxx/api/register";
HttpPost post = new HttpPost(endPoint);
GsonBuilder builder = new GsonBuilder();
Gson gson = builder.create();
ifeanyi.email = "xxxxxxxxxxx#yahoo.com";
ifeanyi.github = "https://xxxxxxxxxxx/code2040Challenge.git";
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
StringEntity data = new StringEntity(gson.toJson(ifeanyi));
post.setEntity(data);
post.setHeader("Content-type", "application/json");
HttpResponse result = httpclient.execute(post);
HttpEntity entity = result.getEntity();
System.out.println(result);
System.out.println(post);
} catch (Exception handle) {
// TODO Auto-generated catch block
handle.printStackTrace();
} finally {
httpclient.close();
}
}
}
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'm trying to use the cookies I get in a response to my post method using HttpClient 4.0.3;
Here is my code:
public void generateRequest()
{
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://mysite.com/login");
httpclient.getParams().setParameter("http.useragent", "Custom Browser");
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION,
HttpVersion.HTTP_1_1);
httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY,
CookiePolicy.BROWSER_COMPATIBILITY);
CookieStore cookieStore = new BasicCookieStore();
HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);
try
{
LOG.info("Status Code: sending");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("email", "john%40gmail.com"));
nameValuePairs.add(new BasicNameValuePair("password", "mypassword"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httppost.setHeader("ContentType", "application/x-www-form-urlencoded");
HttpResponse response = httpclient.execute(httppost, localContext);
HttpEntity entity = response.getEntity();
if (entity != null)
{
entity.consumeContent();
}
iterateCookies(httpclient);
}
catch (ClientProtocolException e)
{
LOG.error("ClientProtocolException", e);
}
catch (IOException e)
{
LOG.error("IOException", e);
}
}
private void iterateCookies(DefaultHttpClient httpclient)
{
List<Cookie> cookies = httpclient.getCookieStore().getCookies();
if (cookies.isEmpty())
{
System.out.println("No cookies");
}
else
{
for (Cookie c : cookies)
{
System.out.println("-" + c.toString());
}
}
}
But I keep getting the No cookies logged out even though when I use web-sniffer.net, I get this response:
Status: HTTP/1.1 302 Found
Cache-Control: private, no-store
Content-Type: text/html; charset=utf-8
Location: http://www.mysite.com/loginok.html
Server: Microsoft-IIS/7.0
X-AspNet-Version: 2.0.50727
Set-Cookie: USER=DDA5FF4E1C30661EC61CFA; domain=.mysite.com; expires=Tue, 08-Jan-2013 18:39:53 GMT; path=/
Set-Cookie: LOGIN=D6CC13A23DCF56AF81CFAF; domain=.mysite.com; path=/ Date: Mon, 09 Jan 2012 18:39:53 GMT
Connection: close
Content-Length: 165
All the examples I've found online that make any sort of sense refer to HttpClient 3.x where you can set the CookiePolicy to IGNORE and handle the Set-Cookie header manually. I can't understand why this is so difficult in 4.x. I need access to the USER hash for a number of reasons. Can anyone please tell me how in the hell I can get access to it?
UPDATE
I have found the following C# code which does the same thing and works correctly.
private static string TryGetCookie(string user, string pass, string baseurl)
{
string body = string.Format("email={0}&password={1}", user, pass);
byte[] bodyData = StringUtils.StringToASCIIBytes(body);
HttpWebRequest req = WebRequest.Create(baseurl) as HttpWebRequest;
if (null != req.Proxy)
{
req.Proxy.Credentials = CredentialCache.DefaultCredentials;
}
req.AllowAutoRedirect = false;
req.Method = "Post";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = bodyData.Length;
using (Stream reqBody = req.GetRequestStream())
{
reqBody.Write(bodyData, 0, bodyData.Length);
reqBody.Close();
}
HttpWebResponse resp1 = req.GetResponse() as HttpWebResponse;
string cookie = resp1.Headers["Set-Cookie"];
if( string.IsNullOrEmpty(cookie))
{
if (0 < resp1.ContentLength)
{
// it's probably not an event day, and the server is returning a singlecharacter
StreamReader stringReader = new StreamReader(resp1.GetResponseStream());
return stringReader.ReadToEnd();
}
return null;
}
return ParseCookie(cookie);
}
I believe my java code is not forming the post request correctly because when I use a URLConnection and print the request header from web-sniffer.net below:
POST /reg/login HTTP/1.1[CRLF]
Host: live-timing.formula1.com[CRLF]
Connection: close[CRLF]
User-Agent: Web-sniffer/1.0.37 (+http://web-sniffer.net/)[CRLF]
Accept-Charset: ISO-8859-1,UTF-8;q=0.7,*;q=0.7[CRLF]
Cache-Control: no-cache[CRLF]
Accept-Language: de,en;q=0.7,en-us;q=0.3[CRLF]
Referer: http://web-sniffer.net/[CRLF]
Content-type: application/x-www-form-urlencoded[CRLF]
Content-length: 53[CRLF]
[CRLF]
email=john%40gmail.com&password=mypassword
I get a response from the server that contains the set-cookies header. Is my java code not generating the request the same as web-sniffer.net?
I have seen a post method generated using this code:
PostMethod authPost = new PostMethod("http://localhost:8000/webTest/j_security_check");
// authPost.setFollowRedirects(false);
NameValuePair[] data = {
new NameValuePair("email", "john%40gmail.com"),
new NameValuePair("password", "mypassword")
};
authPost.setRequestBody(data);
status = client.executeMethod(authPost);
The main difference here being that the NameValuePair data is set in the request body rather than set as the entity. Does this make a difference? Would this produce the correct request header?
Both cookies look suspicious. Both use outdated Netscape cookie draft format. Both have invalid domain attribute value. The LOGIN appears malformed (semicolon is missing after the path attribute) on top of that. So, most likely both cookies got rejected by HttpClient.
You can find out whether this is the case by running HttpClient with the context logging turned on as described here:
http://hc.apache.org/httpcomponents-client-ga/logging.html
One last remark. Generally one should not meddle with cookie policies when using HttpClient 4.x. The default BEST_MATCH policy will automatically delegate processing of cookies to a particular cookie spec implementation based on the composition of the Set-Cookie header value. In order to disable cookie processing entirely one should remove cookie processing protocol interceptors from the protocol processing chain.
Hope this helps.
I believe the problem is that you are mixing two "styles" here: on one hand you create your own BasicCookieStore and put that in your HttpContext; on the other hand, when print the cookies, you loop over the cookie store in the DefaultHttpClient.
So either change the iterateCookies to use your local cookie store, or just use the one provided by the DefaultHttpClient. As you can see in the javadoc of DefaultHttpClient, it should automatically add response cookies to its internal cookie store.
It's always a simple answer! After debugging the C# and another C program I found. I was jumping the gun and doing my own encoding on the email address to remove the # character. This was the problem!!! Nothing else seemed to make a difference whether it was there or not! The code now looks like:
public void postData(final String email, final String password)
{
DefaultHttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(LOGIN_URL);
client.getParams().setParameter("http.useragent", "Custom Browser");
client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
try
{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("email", email));
nameValuePairs.add(new BasicNameValuePair("password", password));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8);
entity.setContentType("application/x-www-form-urlencoded");
post.setEntity(entity);
printHeaders(client.execute(post));
printCookies(client.getCookieStore());
}
catch (ClientProtocolException e)
{
LOG.error("ClientProtocolException", e);
}
catch (IOException e)
{
LOG.error("IOException", e);
}
}
and the output now looks like:
Response Headers:
-Cache-Control: private, no-store
-Content-Type: text/html; charset=utf-8
-Server: Microsoft-IIS/7.0
-X-AspNet-Version: 2.0.50727
-Set-Cookie: USER=3D907C0EB817FD7...92F79616E6E96026E24; domain=.mysite.com; expires=Thu, 10-Jan-2013 20:22:16 GMT; path=/
-Set-Cookie: LOGIN=7B7028DC2DA82...5CA6FB6CD6C2B1; domain=.mysite.com; path=/
-Date: Wed, 11 Jan 2012 20:22:16 GMT
-Content-Length: 165
-Cookie:: [version: 0][name: USER][value: 3D907C0E...E26E24][domain: .mysite.com][path: /][expiry: Thu Jan 10 20:22:16 GMT 2013]
-Cookie:: [version: 0][name: LOGIN][value: 7B7028D...D6C2B1][domain: .mysite.com][path: /][expiry: null]