HTTP ResponseCode 400 - java

I'm using this link that I've changed a little in order to get convert adress to GeoCodes :http://julien.gunnm.org/geek/programming/2015/09/13/how-to-get-geocoding-information-in-java-without-google-maps-api/
I don't understand for some requests I get 400 responseCode and for some i don't have any issue.(I tried these requests and they work fine for me).
For example:
private String getRequest(String url) throws Exception {
url=http://nominatim.openstreetmap.org/search=42+Avenue+Foch,+Saint+Maur+Des+Fossés+France&format=json&addressdetails=1
final URL obj = new URL(url);
final HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestProperty("Content-Length", Integer.toString(url.length()));
con.setRequestMethod("GET");
InputStream is ;
if (con.getResponseCode() != 200) {
is = con.getInputStream();
} else {
is = con.getErrorStream();
}
BufferedReader in = new BufferedReader(new InputStreamReader(is));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
return response.toString();
}

Related

Satang api private http requeat

I'm going to use satang api with java.
This is reference book.
https://docs.satang.pro/authentication
I've completed public request code with java.
private String publicOperation(String operation) throws IOException, BadResponseException {
StringBuilder result = new StringBuilder();
URL url = new URL(baseUrl+operation);
//URL url_ = new URL("https://api.tdax.com/api/orders/?pair=btc_thb");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestProperty("User-Agent", "java client");
con.setRequestMethod("GET");
//https://api.tdax.com/api/orders/?pair=btc_thb
int responseCode=con.getResponseCode();
if(responseCode!=HttpURLConnection.HTTP_OK){
throw new BadResponseException(responseCode);
}
BufferedReader rd = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
result.append(line);
}
rd.close();
return result.toString();
}
Who can make private http request with any program language?
I have the same problem
But I use google sheet to import
function satang(){
var rows=[],obj_array=null;
try {obj_array=JSON.parse(UrlFetchApp.fetch("https://api.tdax.com/api/orders/?pair=btc_thb").getContentText());} catch (e) {obj_array=null;}
if (obj_array!=null){
for (r in obj_array) {rows.push([parseFloat(obj_array[r].bid),parseFloat(obj_array[r].price),parseFloat(obj_array[r].amount),parseFloat(obj_array[r].ask)]);}
var ss=SpreadsheetApp.getActiveSpreadsheet(),sheet=ss.getSheetByName('Satang');ss.getRange("Satang!A1").setValue(new Date());
try {var range=sheet.getRange(2,1,sheet.getLastRow(),6).clearContent();} catch(e) {Logger.log("error");}
if (rows==null||rows=="") {Browser.msgBox("Oops, no data from satang. Please try again"); return false;}
range=sheet.getRange(2,1,rows.length,4); range.setValues(rows);
}
}
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("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("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();
}

C# connect, But java does'nt connect

I'm tring to connect "https://api.tdax.com/api/orders/?pair=btc_thb"
this url is working on chrome, postman.
I can connect this url with C#.
But ca'nt connect with java.
namespace Exchanges.Satang
{
class SatangApi
{
private static class WebApi
{
private static readonly HttpClient st_client = new HttpClient();
static WebApi()
{
st_client.Timeout = TimeSpan.FromSeconds(2);
}
public static HttpClient Client { get { return st_client; } }
public static string Query(string url)
{
var resultString = Client.GetStringAsync(url).Result;
return resultString;
}
}
public static string GetOrders(string symbol)
{
const string queryStr = "https://api.tdax.com/api/orders/?pair=";
var response = WebApi.Query(queryStr + symbol);
return response.ToString();
}
}
}
this C# code working well
but following java code not working, get 403 error.
private String publicOperation(String operation) throws IOException, BadResponseException {
StringBuilder result = new StringBuilder();
URL url = new URL(baseUrl+operation);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
//con.setRequestProperty("Content-Type", "application/json");
con.setRequestMethod("GET");
//https://api.tdax.com/api/orders/?pair=btc_thb
int responseCode=con.getResponseCode();
if(responseCode!=HttpURLConnection.HTTP_OK){
throw new BadResponseException(responseCode);
}
BufferedReader rd = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
result.append(line);
}
rd.close();
return result.toString();
}
Some servers expect a User-Agent header to be present in the request to consider it as a valid request. So you need to add that to your request as follows.
con.setRequestProperty("User-Agent", "My-User-Agent");
int responseCode = con.getResponseCode();
The value of this header (My-User-Agent in the above example) can be set to any String you desire for this endpoint. For example, Postman sets something like PostmanRuntime/7.16.3 for this.
C# might be doing this internally, so you didn't have to set it explicitly.
public String getOrders(SatangCurrencyPairs currencyPair) throws IOException, BadResponseException {
String operation="orders/?pair="+currencyPair.toString();
StringBuilder result = new StringBuilder();
URL url = new URL(baseUrl+operation);
//URL url_ = new URL("https://api.tdax.com/api/orders/?pair=btc_thb");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestProperty("User-Agent", "java client");
con.setRequestMethod("GET");
//https://api.tdax.com/api/orders/?pair=btc_thb
int responseCode=con.getResponseCode();
if(responseCode!=HttpURLConnection.HTTP_OK){
throw new BadResponseException(responseCode);
}
BufferedReader rd = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
result.append(line);
}
rd.close();
return result.toString();
}

Is it possible to fill entities on JHipster from an HTTP?

I just started working with JHipster and I created a .jh file with the entities I want. I would like to fill all the entities by doing an HTTP request to an existing HTTP:PORT that already has my needed information.
I would like to know if it's possible? I'm currently trying with this method that I found online:
private static void sendPOST() throws IOException {
// URL obj = new URL(POST_URL);
Authenticator.setDefault(new Authenticator() {
#Override
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("admin", "admin".toCharArray());
}
});
String url = "http://localhost:8080/api/table-simple-tasks";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
// HttpURLConnection con = (HttpURLConnection) URL.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
// For POST only - START
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(POST_PARAMS.getBytes());
os.flush();
os.close();
// For POST only - END
int responseCode = con.getResponseCode();
System.out.println("POST Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
System.out.println(response.toString());
} else {
System.out.println("POST request not worked");
}
}

Getting connection refused exception with HttpCilent but not when HttpsURLConnection is used

I am getting connection refused exception when i am using the HttpClient to send the request but connection is established when i used the HttpUrlConnection. I want to use HttpClient but not able to figure out what is the reason for connection refusement as same thing works well when i use HttpUrlConnection.
Code when i use HttpClient
public static String httpGet(String urlStr) throws IOException {
HttpClient conn = HttpClientBuilder.create().build();
HttpGet request = new HttpGet(urlStr);
HttpResponse response = conn.execute(request);
System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
// Buffer the result into a string
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity().getContent())
);
StringBuilder sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
return sb.toString();
}
Code when i use HttpUrlConnection
public static String httpGet(String urlStr) throws IOException {
URL url = new URL(urlStr);
HttpsURLConnection conn =
(HttpsURLConnection) url.openConnection();
System.out.println("connection"+conn.getResponseCode());
if (conn.getResponseCode() != 200) {
throw new IOException(conn.getResponseMessage());
}
// Buffer the result into a string
BufferedReader rd = new BufferedReader(
new InputStreamReader(conn.getInputStream())
);
StringBuilder sb = new StringBuilder();
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
conn.disconnect();
return sb.toString();
}

inputStream encoding issues (Special characters: ñ, á,...)

Welcome all, I'm currently working on a web-service and I'm having a lot of trouble to make this method work with characters like ñ, ç, á, è,... It's seems to be related with my Input stream, it doesn't seem to be encoding properly, here's the code:
private static String sendPost(String url, Map<String, JSONObject> params) throws Exception {
String responseString;
StringBuilder urlParameters = new StringBuilder(400);
if (params != null) {
for (Entry<String, JSONObject> entry : params.entrySet()) {
urlParameters.append(entry.getKey()).append("=").append(entry.getValue().toString()).append("&");
}
}
url += urlParameters.toString();
url = url.replace(" ", "%20");
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("charset", "utf-8");
con.setDoOutput(true);
int responseCode = con.getResponseCode();
if (responseCode == HttpStatus.SC_OK) {
BufferedReader in = null;
StringBuffer response = null;
try{
//when i check 'con' all seems to be fine
in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
}finally{
in.close();
}
responseString = response.toString();
} else {
responseString = new StringBuilder(25).append(responseCode).toString();
}
return responseString;
}
Example:
Inside "con" http:\direction.dom\data\W-S\something?param={example:"castaña"}
and InputStream returns: http:\direction.dom\data\W-S\something?param={example:"casta�a"}
Thanks in advance.
This is a really tricky case because you're dealing with HTTP params. Those can be in any encoding that the user enters in your browser.
Based on your example, your user sends his data in something other than UTF-8. It can be ISO-8859-1, ISO-8859-15 or windows-1252.
You can make push your users towards UTF-8 by setting the right HTTP header to your web form: response.setContentType("text/xml; charset=utf-8):
My partner just figure how to solve it:
private static String sendPost(String url, Map<String, JSONObject> params) throws Exception {
String responseString;
StringBuilder urlParameters = new StringBuilder(400);
if (params != null) {
for (Entry<String, JSONObject> entry : params.entrySet()) {
urlParameters.append(entry.getKey()).append("=").append(entry.getValue().toString()).append("&");
}
}
url = url.replace(" ", "%20");
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("accept-charset", "UTF-8");
con.setRequestProperty("content-type", "application/x-www-form-urlencoded; charset=utf-8");
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(wr, "UTF-8"));
writer.write(urlParameters.toString());
writer.close();
wr.close();
int responseCode = con.getResponseCode();
if (responseCode == HttpStatus.SC_OK) {
BufferedReader in = null;
StringBuffer response = null;
try{
in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
}finally{
in.close();
}
responseString = response.toString();
} else {
responseString = new StringBuilder(25).append(responseCode).toString();
}
return responseString;
}

Categories

Resources