AppEngine X-AppEngine-Inbound-AppId received in servlet but not in Endpoint - java

I am using Google Appengine Java endpoints with internal microservices(Modules).
When I execute a call from the endpoints to a module Servlet I receive the X-AppEngine-Inbound-AppId as per documentation(request.getHeader("X-Appengine-Inbound-Appid") and is all good.
When I try to call a module endpoint I don't receive it anymore!!
I am using the same code to execute all the HTTP requests.
public GenericResponse makePOSTRequest(String urlString, Object requestObject, String jSessionId, boolean parseSessionId) {
GenericResponse genericResponse;
String rawPayload = mJsonParser.toJson(requestObject);
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setInstanceFollowRedirects(false);
connection.setConnectTimeout(60000);
connection.setReadTimeout(60000);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Content-Length", String.valueOf(rawPayload.getBytes("UTF-8").length));
if (jSessionId != null) {
connection.setRequestProperty("Cookie", "JSESSIONID=" + jSessionId);
}
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream());
writer.write(rawPayload);
writer.close();
InputStreamReader isr = new InputStreamReader(connection.getInputStream(), "UTF-8");
BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
if (!parseSessionId) {
genericResponse = new GenericResponse(connection.getResponseCode(), sb.toString());
} else {
String responseSessionId = parseSessionId(connection);
genericResponse = new GenericResponse(connection.getResponseCode(), sb.toString(), responseSessionId);
}
return genericResponse;

Related

Spring boot REST gets params to HTTPConnectionURL

I have spring boot application in which I get the streamName as a parameter, but now I don't want it to work in postman, but in another program in which the streamName is String that is created when calling a function. Previously I was giving it as json, but now I want to give it as parameter and I have no idea how can I do it.
This is my Request in Spring boot:
#PostMapping
#ResponseBody
public String addStream(#RequestParam("streamName") String streamName) {
String key = getRandomHexString();
streamService.addStream(new Stream(streamName,key));
return key;
}
and this is in another program where i want to make this method:
public void onHTTPPostRequest(String streamName) throws IOException {
PostResponse postResponse = new PostResponse();
postResponse.setStreamName(streamName);
Gson gson = new Gson();
String jsonString = gson.toJson(postResponse);
getLogger().info("POST Body " + jsonString);
URL pipedreamURL = new URL("http://10.100.2.44:8080/api?streamName=");
HttpURLConnection conn = (HttpURLConnection) pipedreamURL.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json; utf-8");
conn.setRequestProperty("Accept", "application/json");
OutputStream os = conn.getOutputStream();
os.write(jsonString.getBytes("UTF-8"));
os.close();
int responseCode = conn.getResponseCode();
getLogger().info(responseCode);
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
simply add it to the URL string:
URL pipedreamURL = new URL("http://10.100.2.44:8080/api?streamName=" + streamName);

Malformed request exception when trying to send GET request

I'm trying to connect to GDAX using their REST API.
I first want to do something very simple, i.e. getting historic rates.
I tried this:
private static final String GDAX_URL = "https://api.gdax.com";
public String getCandles(final String productId, final int granularity) {
HttpsURLConnection connection = null;
String path = "/products/" + productId + "/candles";
try {
//Create connection
URL url = new URL(GDAX_URL);
connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("granularity", String.valueOf(granularity));
connection.setUseCaches(false);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(path);
wr.close();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
StringBuffer response = new StringBuffer();
String line;
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
System.out.println(response.toString());
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (connection != null) {
connection.disconnect();
}
}
return null;
}
But I get a 400 code in return "Bad Request – Invalid request format".
My problem is with the passing of the path "/products//candles" and the parameters (e.g. granularity).
I don't understand what should go in the request properties and in the message itself, and in what form.
I managed to make it work like this:
URL url = new URL(GDAX_URL + path + "?granularity="+granularity);
connection = (HttpsURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Content-Type", "application/json");
Not sure how to use the DataOutputStream, so I just removed it. At least it works.

.net rest service with JSON string and consumed with java client

I want to consume the .net JSON string web services in java. I am getting bad request error always but through SOAP UI i am getting the response. Any one suggest me how to consume the .net rest services in java.
"{"\DocumentId\":"\29292\","\Note\":"\jaasBook\"}"
String uri = "http://example.com/service.asmx/GetInfo";
URL url = new URL(uri);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Accept", "application/json");
connection.setChunkedStreamingMode(0);
connection.connect();
byte[] parameters = {"\DocumentId\":"\29292\","\Note\":"\jaasBook\"}".getBytes("UTF-8");
DataOutputStream os = new DataOutputStream(connection.getOutputStream());
os.write(parameters);
os.close();
InputStream response;
if(connection.getResponseCode() == 200){response = connection.getInputStream();}
else{response = connection.getErrorStream();}
InputStreamReader isr = new InputStreamReader(response);
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(isr);
String read = br.readLine();
while(read != null){
sb.append(read);
read = br.readLine();
}
At first glance it looks like you are improperly escaping the JSON string:
byte[] parameters = "{\"DocumentId\":\"29292\",\"Note\":\"jaasBook\"}".getBytes("UTF-8");
Note that the backslash comes before each double-quote you need to escape.
use this code to send and recieve response
public static String makeHttpCall(String strRequest)
throws ServiceException {
try {
String response = null;
URL url = new URL(
"http://example.com/service.asmx/GetInfo");
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
DataOutputStream dstream = new DataOutputStream(
connection.getOutputStream());
dstream.writeBytes(strRequest);
dstream.flush();
dstream.close();
StringBuffer sb = new StringBuffer();
InputStreamReader content = new InputStreamReader(
connection.getInputStream());
for (int i = 0; i != -1; i = content.read()) {
sb.append((char) i);
}
response = sb.toString().substring(1, sb.toString().length());
System.out.println("Response:");
System.out.println(response);
return response;
} catch (MalformedURLException e) {
throw new ServiceException("MalformedURLException", e);
} catch (ProtocolException e) {
throw new ServiceException("ProtocolException", e);
} catch (IOException e) {
throw new ServiceException("IOException", e);
}
}
then use Gson lib to parse Json to object
Finally i consumed the .net json web service with java client. Thanks every one for the support.
public class JsonRestEx {
public static void main(String[] args) {
try {
StringBuilder stringBuilder = new StringBuilder("\"");
stringBuilder.append("{");
stringBuilder.append("\\");
stringBuilder.append("\"");
stringBuilder.append("DocumentDefinition");
stringBuilder.append("\\");
stringBuilder.append("\"");
stringBuilder.append(":");
stringBuilder.append("\\");
stringBuilder.append("\"");
stringBuilder.append("google.com||CC/APP/44||Loan Application file||CAS3333||3333||Loan|| Loan||AC222||LN8888");
stringBuilder.append("\\");
stringBuilder.append("\"");
stringBuilder.append(",");
stringBuilder.append("\\");
stringBuilder.append("\"");
stringBuilder.append("correlationId");
stringBuilder.append("\\");
stringBuilder.append("\"");
stringBuilder.append(":");
stringBuilder.append("\\");
stringBuilder.append("\"");
stringBuilder.append("43754309657043769854");
stringBuilder.append("\\");
stringBuilder.append("\"");
stringBuilder.append("}");
stringBuilder.append("\"");
System.out.println("FINAL STR: "+ stringBuilder.toString());
String urlString="http://12.2.2.0/RS/dfs.svc/sfd";
HttpPost request = new HttpPost(urlString);
StringEntity entity = new StringEntity(stringBuilder.toString(), "UTF-8");
entity.setContentType("application/json;charset=UTF-8");
entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-8"));
request.setEntity(entity);
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
int statusCode = response.getStatusLine().getStatusCode();
System.out.println("statusCode: "+ statusCode);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line = "";
while ((line = rd.readLine()) != null) {
System.out.println(line);
}
}catch (Exception e) {
e.printStackTrace();
}
}
}

Flask not receiving POST from Android

I used to use DefaultHttpClient for my networking code, but decided to change to HttpURLConnection.
I have searched for other questions on how to send POST messages (eg How to add parameters to HttpURLConnection using POST), but for some reason my Flask app always gives me error 400.
When I use logcat, it indeed displays that my POST message is "username=asdf&password=asdf". I include the code below. Also, if I initialized the cookieManager in the method that called this method (makeServiceCall), will returning cookieManager keep my session for subsequent calls to makeServiceCall?
public CookieManager makeServiceCall(CookieManager cookieManager, String urlString, int method, List<NameValuePair> db) {
String charset = "UTF-8";
try {
URL url = new URL(urlString);
if (method == POST) {
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
if (db != null) {
try {
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setChunkedStreamingMode(0);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Accept-Charset", charset);
urlConnection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
OutputStream out = new BufferedOutputStream(urlConnection.getOutputStream());
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(out, charset));
Log.d("log", "> " + getQuery(db));
writer.write(getQuery(db));
writer.flush();
writer.close();
out.close();
//Get Response
InputStream in = urlConnection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(in));
String line;
StringBuffer response = new StringBuffer();
while((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
Log.d("Read attempt: ", "> " + response.toString());
}
finally {
urlConnection.disconnect();
}
}
}
etc.
Flask code:
def login():
error = None
if request.method == 'POST':
if request.form['username'] != app.config['USERNAME']:
error = 'Invalid username'
elif request.form['password'] != app.config['PASSWORD']:
error = 'Invalid password'
else:
session['logged_in'] = True
flash('You were logged in')
return redirect(url_for('show_entries'))
return render_template('login.html', error=error)

Sending post request to https

I need to send a post request to a https address. I have a function that sends post messages currectly but i cant seem to make it work for https.
public static String serverCall(String link, String data){
HttpURLConnection connection;
OutputStreamWriter request = null;
URL url = null;
String response = null;
String parameters = data;
try
{
url = new URL(link);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "text/xml");
connection.setRequestMethod("POST");
request = new OutputStreamWriter(connection.getOutputStream());
request.write(parameters);
request.flush();
request.close();
String line = "";
InputStreamReader isr = new InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
// Response from server after process will be stored in response variable.
response = sb.toString();
isr.close();
reader.close();
}
catch(IOException e)
{
// Error
}
return response;
}
i have tryed using HttpsURLConnection insted of HttpURLConnection, i am still getting null from my server.
you should call connect();
....
connection.setRequestMethod("POST");
connection.connect();
....

Categories