I am using the following method for getting time from server with a Post request.
String result = "";
URL url = null;
InputStream stream = null;
HttpURLConnection urlConnection = null;
try {
url = new URL("http://192.168.118.2/myapi");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
String data = URLEncoder.encode("time", "UTF-8")
+ "=" + URLEncoder.encode("Submit", "UTF-8");
urlConnection.connect();
OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
wr.write(data);
wr.flush();
stream = urlConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"), 8);
String line = "";
while((line = reader.readLine()) != null)
result += line;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
}
Toast.makeText(this, result, Toast.LENGTH_SHORT).show();
Here is php script
<?php
if(isset($_POST["time"]))
echo "Time";
else
echo "Invalid Request";
But when i call post method, i get resut "Invalid Request".
I almost searched every stackoverflow threads but none of them working, i really wonder what is the problem.
A few things to try.
1) Add the following to your manifest.
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
2) change your PHP file
<?php
$time = urldecode($_POST['time']);
if($time === NULL) {
echo "invalid";
} else {
echo "time";
}
?>
I fixed the problem with following changes;
data = "time=Submit";
...
...
...
url = new URL("http://192.168.118.2/myapi/index.php");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setInstanceFollowRedirects( false );
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded");
urlConnection.setRequestProperty( "charset", "utf-8");
urlConnection.setRequestProperty( "Content-Length", Integer.toString( data.getBytes().length ));
urlConnection.setUseCaches( false );
urlConnection.setConnectTimeout(1000);
urlConnection.setReadTimeout(1000);
...
...
...
Related
I've built java code to use satang "orders/user" api.
But got 405 error.
Please help me.
I've built placeLimitOrder() function.
And used successfully.
Then getUserOrders() function also made with same rult.
But this function got 405 error.
I can't find the reason.
public String getUserOrders (String pair,String limit,String offset,String status,String side)
{
String req="limit="+limit+"&offset="+offset+"&pair="+pair+"&side="+side+"&status="+status;
String operation="orders/user";
String signature=getSignature(req);
URL url = new URL(baseUrl+operation);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoOutput( true );
con.setInstanceFollowRedirects( false );
con.setRequestProperty("Authorization", "TDAX-API "+this.key);
con.setRequestProperty("Signature",signature);
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("charset", "utf-8");
con.setRequestProperty("User-Agent", "java client");
con.setUseCaches( false );
JsonObject obj=new JsonObject();
obj.addProperty("limit", limit);
obj.addProperty("offset", offset);
obj.addProperty("pair", pair);
obj.addProperty("side", side);
obj.addProperty("status", status);
String json=obj.toString();
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(json);
wr.flush();
wr.close();
int responseCode=con.getResponseCode();
if(responseCode!=HttpURLConnection.HTTP_OK){
throw new BadResponseException(responseCode);
}
BufferedReader rd = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder result = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
result.append(line);
}
rd.close();
return result.toString();
}
Following code working well.
I can't find the reason.
public String placeLimitOrder(String amount,String pair,String price,String side) throws IOException, BadResponseException
{
Long lnonce=new Date().getTime();
String nonce=lnonce.toString();
String req="amount="+amount+"&nonce="+nonce+"&pair="+pair+"&price="+price+"&side="+side+"&type=limit";
String operation="orders/";
String signature=getSignature(req);
URL url = new URL(baseUrl+operation);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setDoOutput( true );
con.setInstanceFollowRedirects( false );
con.setRequestProperty("Authorization", "TDAX-API "+this.key);
con.setRequestProperty("Signature",signature);
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("charset", "utf-8");
con.setRequestProperty("User-Agent", "java client");
con.setUseCaches( false );
JsonObject obj=new JsonObject();
obj.addProperty("amount", amount);
obj.addProperty("nonce", nonce);
obj.addProperty("pair", pair);
obj.addProperty("price", price);
obj.addProperty("side", side);
obj.addProperty("type", "limit");
String json=obj.toString();
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(json);
wr.flush();
wr.close();
int responseCode=con.getResponseCode();
if(responseCode!=HttpURLConnection.HTTP_OK){
throw new BadResponseException(responseCode);
}
BufferedReader rd = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder result = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
result.append(line);
}
rd.close();
return result.toString();
}
public String getUserOrders(String pair,String limit,String offset,String status,String side) throws IOException, BadResponseException
{
String req="limit="+limit+"&offset="+offset+"&pair="+pair+"&side="+side+"&status="+status;
String operation="orders/user?"+req;
String signature=getSignature("");
URL url = new URL(baseUrl+operation);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setDoOutput( true );
con.setInstanceFollowRedirects( false );
con.setRequestProperty("Authorization", "TDAX-API "+this.key);
con.setRequestProperty("Signature",signature);
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("charset", "utf-8");
con.setRequestProperty("User-Agent", "java client");
con.setUseCaches( false );
int responseCode=con.getResponseCode();
if(responseCode!=HttpURLConnection.HTTP_OK){
throw new BadResponseException(responseCode);
}
BufferedReader rd = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder result = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
result.append(line);
}
rd.close();
return result.toString();
}
So if you are trying to do GET to https://api.tdax.com/api/orders/user
Headers should include:
Signature
Authentication
Query Parameters:
pair
limit
offset
status
side
From your code, it looks like you have put everything to the Signature.
Link to API docs
This is what you should fix:
URL. It should look like:
https://api.tdax.com/api/orders/user?pair=pairValue&limit=limitValue&offset=... add all the parameters and insert values.
Change request method to GET
Double-check your headers (Signature, Authentication).
Error code 405 - "bad request", which means most likely your request URL is bad. After you will fix URL, you should be able to get a different response code like 403/401 which should indicate that something is wrong with signature or authentication. In the best-case scenario, you will get 200 and then try to parse the JSON response.
Also, I don't recommend you to use HttpURLConnection, Generally, it’s NOT recommended to use this class, because the codebase is very old and outdated, it may not supports the new HTTP/2 standard, in fact, it’s really difficult to configure and use this class. Please consider using OkHttp, Apache HttpClient or other libraries.
I brief description of what I'm doing, I'm automating creating incidents in ServiceNow using API. I have tested with POSTMAN first and it works fine.
Now after I wrote the code, I try to post data, I got no respond from the server. what could be the problem?
if (method.equals("POST") )
{
url+= "api/now/table/incident";
}
else if (method.equals("GET")|| method.equals("PUT"))
{
url+= "api/now/table/incident/" + incident.getSys_id();
}
URL request_url = new URL(url);
CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
connection = (HttpsURLConnection) request_url.openConnection();
// ((HttpsURLConnection) connection).setSSLSocketFactory(sslsocketfactory);
if (method.equals("POST") || method.equals("PUT"))
{
connection.setRequestProperty("Content-Type", "application/json");
}
else
{
connection.setRequestProperty("Accept", "application/json");
}
connection.setRequestProperty("User-Agent", "Mozilla/5.0"); // this was suggested as solution, but doesn't work.
connection.setRequestMethod(method);
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestProperty("Authorization", "Basic "+encoded);
if (method.equals("POST") || method.equals("PUT"))
{
JSONObject json = new JSONObject();
json.put("short_description",incident.getShort_description());
json.put("description", incident.getDescription());
json.put("assignment_group",incident.getAssignment_group());
json.put("priority",incident.getPriority());
json.put("impact",incident.getImpact());
OutputStream os = connection.getOutputStream();
os.write(json.toJSONString().getBytes(StandardCharsets.UTF_8));
os.close();
}
// read the respond
httpsCode = connection.getResponseCode();
if (httpsCode == HttpsURLConnection.HTTP_OK || httpsCode == 201)
{
//Read
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8));
String lines = null;
StringBuilder stringBuilder = new StringBuilder();
while ((lines = bufferedReader.readLine()) != null)
{
stringBuilder.append(lines);
}
bufferedReader.close();
result = stringBuilder.toString();
JSONParser parser = new JSONParser();
JSONObject json = (JSONObject) parser.parse(result);
String incident_number = json.get("incident_number").toString();
String sys_id = json.get("sys_id").toString();
incident.setIncident_number(incident_number);
incident.setSys_id(sys_id);
return null;
}
the error is related to timeout, a posted solution suggested to set up the header to a browser type. but that's also didn't work.
public static String request(String httpUrl, String httpArg) {
BufferedReader reader = null;
String result = "";
StringBuffer sbf = new StringBuffer();
httpUrl = httpUrl + "?" + httpArg;
try {
URL url = new URL(httpUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("apikey", myAPpiKey);
conn.connect();
if (conn.getResponseCode() == 200) {
InputStream is = conn.getInputStream();
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String strRead = null;
while ((strRead = reader.readLine()) != null) {
sbf.append(strRead);
sbf.append("\r\n");
}
reader.close();
result = sbf.toString();
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
Above code worked well on Android 5.1 and Android 6.0, and it returned correct result that I want. But when I ran these on Android 4.4, using the same params, it returned different result. I have tried several times, and attached debugger to the process. I found that the connection could be built successfully, and the ResponseCode was also 200.
I guess there must be something wrong with the HttpURLConnection params, so that the server returned different result. Did I set the params in a way that could work on Android 5.1 and 6.0 but not on 4.4? Can anybody tell me where did I do wrong?
Try below code:
URL url = new URL(httpUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setChunkedStreamingMode(0);
conn.setDoInput(true);
conn.setRequestMethod("GET");
conn.setRequestProperty("apikey", myAPpiKey);
if (conn.getResponseCode() == 200) {
InputStream is = conn.getInputStream();
.........
}
It works for me. Hope it will work.
I have a cURL command I want to translate in Java
curl -H "Key: XXX" -d url=http://www.google.com http://myapi.com/v2/extraction?format=json
It works fine.
I started to do in Java: (CODE EDITED, it works)
try {
// POST
System.out.println("POSTING");
URL url = new URL("http://myapi.com/v2/extraction?format=json");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Key", "XXX");
String data = "http://www.google.com";
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write("url=" +data);
writer.close();
int responseCode = connection.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + data);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println("REPOSNE" +response.toString());
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
// OK
} else {
// Server returned HTTP error code.
}
} catch (MalformedURLException e) {
// ...
} catch (IOException e) {
// ...
}
But I don't know how to set my arguments.
Thanks for your help.
Jean
If you mean to set a header field Key with value XXX you can use the setRequestProperty
ie
conn.setRequestProperty("Key", "XXX");
If you want to send data, use
String data = "url=http://www.google.com";
conn.setRequestProperty("Content-Length", "" + Integer.toString(data.getBytes().length));
EDIT:-
For posting data as form url encoded, try the following code
String data = "url=" + URLEncoder.encode("http://www.google.com", "UTF-8");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
wr.write(data.getBytes());
In official documentation of Google Translate Api for Java it says that we can use post-method to send more than 2K characters. https://developers.google.com/translate/v2/using_rest
However when I try to translate text more than 2k length I get error 414 (Request-URI Too Large).
StringBuilder sb = new StringBuilder();
HttpURLConnection connection = null;
try {
URL url = new URL("https://www.googleapis.com/language/translate/v2");
String urlParameters = "key=" + apiKey + "&source=" + shortLang1 +
"&target=" + shortLang2 + "&q=" + URLEncoder.encode(lyrics, "UTF-8");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches (false);
connection.addRequestProperty("X-HTTP-Method-Override", "GET");
DataOutputStream wr = new DataOutputStream (connection.getOutputStream ());
wr.writeBytes (urlParameters);
wr.flush ();
wr.close ();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
if (connection.getResponseCode() != 200) {
return null;
}
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
UPDATE: I got it, the code above is right. Finally I realize that I got this error not from Google Translate service but from my proxy on Google App Engine.
What the document you linked to is saying is that you use the POST method and you put the parameters into the request body ... not the request URL.
Reference:
How are parameters sent in an HTTP POST request?