I'm trying to connect to a website and to send many different post requests through different pages all over the website.
I've reached the first step:connect the website.
But now, I need to change the request url and keeping the same httpURLConnection.
For now my code is:
//openning the connection to the website
URL url = new URL("http://path/to/the/website");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
//preparing the post arguments
Map<String, Object> params = new HashMap<>();
params.put("Action", "connect_user");
params.put("login", "login");
params.put("password", "password");
StringBuilder sb = new StringBuilder();
for (Entry<String, Object> e : params.entrySet()) {
if (sb.length() != 0)
sb.append('&');
sb.append(URLEncoder.encode(e.getKey(), "UTF-8"));
sb.append('=');
sb.append(URLEncoder.encode(String.valueOf(e.getValue()), "UTF-8"));
}
//writing the request and sending
BufferedOutputStream writer = new BufferedOutputStream(conn.getOutputStream());
writer.write(sb.toString().getBytes(Charset.forName("UTF-8")));
writer.flush();
At this step i'm connected and sucessfully logged in.
What I need to do now is to redirect the same connection to a second url.
Thanks.
Related
Currently there is a desktop application in java that when pressing a button opens a browser with a URL (), the parameters go in the URL so when opening the browser they are read and does what it does (show example: show a beautiful web and print the name and age and year of birth). http: // localhost: 8090 / testvisor? name = john & age = 23Now, the requirement is that the parameters are not visible in the url, that is, that the request is made by POST and not by GET. I managed to open the browser with that URL, but not send the POST request with the name and age. I also managed to send the POST request but I was unable to open the browser with those "obtained" data after the request was sent. That is, the browser opens but no data is detected as in the case of sending the data by url.Note: the method in charge of receiving by POST is fine, since I can send the request and it arrives without problems.Code with which I send the POST request (works):
`URL url = new URL("http://localhost:8090/pruebavisor");
Map<String, Object> params = new HashMap<>();
params.put("nombre", "juan");
params.put("edad", "23");
int tamano = params.size();
StringBuilder postData = new StringBuilder();
for (Map.Entry<String, Object> param : params.entrySet()) {
postData.append("\"").append(param.getKey()).append("\":");
postData.append("\"").append(String.valueOf(param.getValue())).append("\",");
if (tamano == (tamano - tamano) + 1) {
postData = new StringBuilder("{" + postData.substring(0, (postData.length() - 1)) + "}");
}
tamano--;
}
byte[] postDataBytes = postData.toString().getBytes("UTF-8");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
conn.setDoOutput(true);
conn.setDoOutput(true);
conn.getOutputStream().write(postDataBytes);
Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
for (int c = in.read();c != -1; c = in.read()) {
System.out.print((char) c);
}`
When I Post Json Data using HttpURLConnection, the server on the other side receive a String with backslashes.
The setRequestProperty are set as:
conn.setRequestProperty("Content-Type","application/json");
This is my code
HttpURLConnection connection = null;
Gson gson = new Gson();
String jsonEnvio = gson.toJson(object);
URL url = new URL(urlSend);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(method);
if (headers != null)
{
for (Map.Entry<String, String> entry : headers.entrySet()) {
connection.setRequestProperty(entry.getKey(), entry.getValue());
}
}
connection.setUseCaches(false);
connection.setDoOutput(true);
connection.setConnectTimeout(30000);
if (object != null)
{
connection.setRequestProperty("Content-Length", Integer.toString(jsonEnvio.getBytes().length));
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes(jsonEnvio);
wr.close();
}
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
This is the string at variable jsonEnvio
{"codOrdemComplexa":"12346544","codFornecedor":"56","codEtapaProcesso":"622635","codTipoElemento":"6","codTipoProjeto":"1","hash":"780fbd8103abe35899d219e8856123a6","nomeArquivo":"OrdemDeServico_12346544_Wed Feb15 18:05:25 BRST 2017","dataColetaEvidencias":"Feb 15, 2017 6:05:25 PM"}
This is the string that the Server on the other side receive
{\"codOrdemComplexa\":\"12346544\",\"codFornecedor\":\"56\",\"codEtapaProcesso\":\"622635\",\"codTipoElemento\":\"6\",\"codTipoProjeto\":\"1\",\"hash\":\"780fbd8103abe35899d219e8856123a6\",\"nomeArquivo\":\"OrdemDeServico_12346544_Wed Feb15 18:05:25 BRST 2017\",\"dataColetaEvidencias\":\"Feb 15, 2017 6:05:25 PM\"}
The server on the other side respond that this is not a valid Json.
I need help to figure out what I need to change to fix that.
Using JDK 1.8.0_121
I know what is the HTTP header and how the HTTP data format , I also know how to make a HTTP post from Java ,
like
StringBuffer result = new StringBuffer();
PrintWriter out = null;
BufferedReader in = null;
StringBuffer result = new StringBuffer();
try {
URL realUrl = new URL("http://somesite/somepage.htm");
URLConnection conn = realUrl.openConnection();
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setDoOutput(true);
conn.setDoInput(true);
out = new PrintWriter(conn.getOutputStream());
out.print(param);
out.flush();
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result.append(line);
}
} catch (Exception e) {
e.printStackTrace();
}
I can use some code like this write stream to web server , and read stream also .
Here is my question .
What is the HTTP POST method really do , I mean how does the client communicate to web server ?
What will happen if the web server only read the HTTP POST header and don't read the stream from client ?
Does the stream will stuck in somewhere ?
Thanks .
I'm having the hardest time, what I want is for my android application to send a STRING to my server, my server will then choose a function based upon what STRING was sent in PHP. Once the function is done, it will return a JSONObject. I don't want to use any Deprecated methods. I'm trying to implement the sending a STRING to the server to parse and use an appropriate function in PHP then send a JSON back to my android application. Can anyone please show some code from the android side?
So what I'm looking for is, help with the Android code to send a STRING to the server, then read the response from the server which will be a JSON.
For Android you can use HTTP Connection URL. An example is mentioned here How to add parameters to HttpURLConnection using POST
URL url = new URL("http://yoururl.com");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", "Chatura"));
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getQuery(params));
writer.flush();
writer.close();
os.close();
conn.connect();
..
private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException
{
StringBuilder result = new StringBuilder();
boolean first = true;
for (NameValuePair pair : params)
{
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
}
return result.toString();
}
For PHP just accept a post request which is coming form Andrid as below
<?php
echo '{ "name" = "Hello ' . htmlspecialchars($_POST["name"]) . '"}';
?>
I am trying to create java desktop app for online shopping. So far I am able to login, select product, and select check out
using httpsurlconnect. but after checkout site redirects to bank payment gateway. And i always get response unable to process your request after redirect.
I think this is because payment gateway uses 2-way mutual negotiation (not sure). So how can i create 2-way mutual negotiation on fourth request.
I have done a bit research on internet. i found that it requires keystore.jks and truststore.jks. I asume that JDK comes with CA truststore which can accept server certificate.
I need keystore.jks file with client key and certificate. if i create self signed cert, will the server accept it. Server users verisigned CA cert and i have no control over server.
How can i get client keystore.jks and implement handshake on fourth request. Sample code of my implementaion is given below.
public void query(){
//request 1
String url_1 = "https://www.shop.com/login.do";
String ref_1 = "https://www.shop.com/";
Map<String, String> post = new HashMap<String, String>();
post.put("userName", var.userName);
post.put("password", var.password);
String new_post_1 = Generate_post(post);
Connect(url_1, ref_1, new_post_1);
//request 2
String url_2 = "https://www.shop.com/select_product.do";
String ref_2 = "https://www.shop.com/login.do";
Map<String, String> post = new HashMap<String, String>();
post.put("product", var.Name);
post.put("id", var.id);
post.put("price", var.price);
String new_post_2 = Generate_post(post);
Connect(url_2, ref_2, new_post_2);
//request 3
String url_3 = "https://www.shop.com/checkout.do";
String ref_3 = "https://www.shop.com/select_product.do";
Map<String, String> post = new HashMap<String, String>();
post.put("product", var.Name);
post.put("id", var.id);
post.put("total_price", var.total_price);
post.put("checkout", var.checkout);
String new_post_3 = Generate_post(post);
Connect(url_3, ref_3, new_post_3);
//request 4
String url_4 = "https://secure.payment.com/gateway.do";
String ref_4 = "https://www.shop.com/checkout.do";
Map<String, String> post = new HashMap<String, String>();
post.put("total_price", var.total_price);
post.put("bank", var.bank);
post.put("confirm", var.confirm);
String new_post_4 = Generate_post(post);
Connect(url_4, ref_4, new_post_4);
}
Connnect method:
void Connect(String https_url, String referal, String query) throws IOException{
URL url = new URL(https_url);
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL));
//set properties
HttpsURLConnection.setFollowRedirects(true);
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestMethod("POST");
con.setUseCaches(false);
con.setAllowUserInteraction(false);
con.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; rv:8.0) Gecko/20100101 Firefox/8.0");
con.setRequestProperty("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
con.setRequestProperty("Accept-Language","en-us,en;q=0.5");
con.setRequestProperty("Connection","keep-alive");
con.setRequestProperty("charset","iso-8859-1");
con.setRequestProperty("Referer",referal);
con.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
con.setRequestProperty("Content-Length",String.valueOf(query.length()));
// Create Output streams
BufferedWriter outStream = new BufferedWriter(new OutputStreamWriter(con.getOutputStream()));
outStream.write(query);
outStream.flush();
outStream.close();
if(con.getResponseCode()==HttpsURLConnection.HTTP_OK ){
// Create Input streams
InputStreamReader in = new InputStreamReader(con.getInputStream());
BufferedReader inStream = new BufferedReader(in, 1024*24);
String html;
StringBuffer page = new StringBuffer();
while((html = inStream.readLine()) != null) {
page.append(html+"\n"); }
inStream.close();
}else{
System.out.println(con.getHeaderFields());
InputStreamReader in = new InputStreamReader(con.getErrorStream());
BufferedReader inStream = new BufferedReader(in);
String html;
StringBuffer page = new StringBuffer();
while((html = inStream.readLine()) != null) {
page.append(html+"\n"); }
}
con.disconnect();
}