I want something like this, but with a file attachment, so i can send an embed and under it the image. It doesnt have to like this exactly, but it should like something like this: enter image description here
package com.StrgC;
import java.io.OutputStream;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
public class WarningSending {
public static void SendWarning() {
///////////////////////////////////////////////
// CONFIG
String tokenWebhook = "";
String title = "";
String message = "";
///////////////////////////////////////////////
String jsonBrut = "";
jsonBrut += "{\"embeds\": [{"
+ "\"title\": \""+ title +"\","
+ "\"description\": \""+ message +"\","
+ "\"color\": 15925248"
+ "}]}";
try {
URL url = new URL(tokenWebhook);
HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
con.addRequestProperty("Content-Type", "application/json");
con.addRequestProperty("User-Agent", "Java-DiscordWebhook-BY-Gelox_");
con.setDoOutput(true);
con.setRequestMethod("POST");
OutputStream stream = con.getOutputStream();
stream.write(jsonBrut.getBytes());
stream.flush();
stream.close();
con.getInputStream().close();
con.disconnect();
} catch (Exception e) {
e.printStackTrace()
}
}
}
Related
After running the post request with JSON I have HTTP Error 400 Bad request.
I think the problem is in the JSON string but I do not now how to fix it.
package Curl;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.http.HttpRequest;
import java.nio.charset.StandardCharsets;
public class Http_Con {
private static HttpURLConnection connection;
public static void main(String[] args) throws IOException {
Http_Con connection = new Http_Con();
//call the getRequest method
connection.GetRequest();
//call the postRequest
connection.PostRequest();
}
public void GetRequest() {
BufferedReader reader;
String lines;
StringBuilder responseContent = new StringBuilder();
try {
//set the url
URL url = new URL("http://192.168.0.104:4041/iot/devices");
//open the connection
connection = (HttpURLConnection) url.openConnection();
//set the request method and timeout
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
//set request properties(in this case headers)
connection.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Fiware-Service", " myHome");
connection.setRequestProperty("Fiware-ServicePath", "/environment");
//get the response code(200 should be OK)
int status = connection.getResponseCode();
if (status > 299) {
reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
while ((lines = reader.readLine()) != null) {
responseContent.append(lines);
}
reader.close();
} else {
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((lines = reader.readLine()) != null) {
responseContent.append(lines);
}
reader.close();
}
//print the response content(result)
System.out.println(responseContent.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
public void PostRequest() throws IOException {
//set the url
String url = "http://192.168.0.104:4041/iot/devices";
URL obj = new URL(url);
//open the connection
HttpURLConnection connection = (HttpURLConnection) obj.openConnection();
//set the method type(POST OR GET)
connection.setRequestMethod("POST");
//set hte request properties(headers etc.)
connection.setRequestProperty("Content-Type", "application/json; utf-8");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Fiware-Service"," myHome");
connection.setRequestProperty("Fiware-ServicePath","/environment");
//make sure that will be able to write content to the connection output stream
connection.setDoOutput(true);
//Json formatted input string
String jsonInputString = "{\n" +
" \"devices\": [\n" +
" {\n" +
" \"device_id\": \"sensor01\",\n" +
" \"entity_name\": \"LivingRoomSensor\",\n" +
" \"entity_type\": \"multiSensor\",\n" +
" \"attributes\": [\n" +
" { \"object_id\": \"t\", \"name\": \"Temperature\", \"type\": \"celsius\" },\n" +
" { \"object_id\": \"l\", \"name\": \"Luminosity\", \"type\": \"lumens\" }\n" +
" ]\n" +
" }\n" +
" ]\n" +
"}";
try(OutputStream os = connection.getOutputStream()) {
byte[] input = jsonInputString.getBytes(StandardCharsets.UTF_8);
os.write(input, 0, input.length);
}
try(BufferedReader br = new BufferedReader(
new InputStreamReader(connection.getInputStream(), StandardCharsets.UTF_8))) {
StringBuilder response = new StringBuilder();
String responseLine = null;
while ((responseLine = br.readLine()) != null) {
response.append(responseLine.trim());
}
//print the result
System.out.println(response.toString());
}
}
}
I Think you can use Fidder application to do something, which find Questions so fast. Due to 400 statusCode, Liking Cookie lost, params lost, request method lost .... trust think for you help!
I have been told to execute this java program which is linked to a virtual number, when you run it, the output is a number code or whatever it is that i sent the number in sms.
I am using selenium and maven and also in the eclipse program and was told to use the testng plugin. They asked me to use #test annotations in an .xml file to execute it.
Im knew to programming and to be honest i have no idea how to write the xml file in order to run this and when i ask the person who told me to do this all they do is say google it and i have tried but i havent found anything.
the code is:
package utility;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.HttpsURLConnection;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.Assert;
import org.apache.commons.codec.binary.Base64;
//import sun.misc.BASE64Encoder;
public class APIcall {
// String MobileNo = ""; // virtual mobile no. (From message media)
private final String USER_AGENT = "Mozilla/5.0";
// Msg media Account:
// Password:
String name = ;
String password = ;
String authString = name + ":" + password;
//String authStringEnc = new BASE64Encoder().encode(authString.getBytes());
String authStringEnc = new Base64().encodeBase64String(authString.getBytes());
static String URL = "https://api.messagemedia.com";
String getURI = "/v1/replies";
static String postURI = "/v1/replies/confirmed";
static Client client = ClientBuilder.newClient();
public Data getRequest() {
Response response = (Response) client.target(URL +
getURI).request(MediaType.APPLICATION_JSON_TYPE)
.header("Authorization", "Basic " + authStringEnc).get();
String body = response.readEntity(String.class);
// System.out.println("status: " + response.getStatus());
// System.out.println("headers \n: " + response.getHeaders());
System.out.println("body: \n" + body);
JSONObject json = new JSONObject(body);
JSONArray reply = (JSONArray) json.get("replies");
List<String> ids = new ArrayList<String>();
for (int idx = 0; idx < reply.length(); idx++) {
// ids.add(replyIds.get(idx).toString());
ids.add(reply.getJSONObject(idx).getString("reply_id"));
}
Assert.assertEquals(200, response.getStatus());
/*
* String OTPcode = (String) body.substring(body.lastIndexOf(' ') + 1); OTPcode
* = OTPcode.substring(0, 6).trim();
*/
String getContent = reply.getJSONObject(0).getString("content");
System.out.println(getContent);
String[] content = getContent.split(" ");
String code = content[content.length - 1];
// System.out.println("OTP code : " + code);
// System.out.println("List of replies : " + ids);
return new Data(code, ids, getContent);
//JSONException
}
public final class Data {
public String otp;
public List<String> list;
public String getContent;
public Data(String otp, List list, String getContent) {
this.otp = otp;
this.list = list;
this.getContent = getContent;
}
}
public void postRequest() {
/*
* Post request : Add reply ids recieved from GET request and pass it in body
* with POST request to confirm replies
*/
List<String> ids = getRequest().list;
String postStr = "{ \"reply_ids\":[";
for (String id : ids) {
postStr += "\"" + id + "\", ";
}
postStr += " ]}";
StringBuilder postString = new StringBuilder(postStr);
postString.replace(postStr.lastIndexOf(","),
postStr.lastIndexOf(",") + 1, "");
postStr = postString.toString();
// System.out.println("Reply id list : " + postStr);
Response response = client.target(URL + postURI)
.request(MediaType.APPLICATION_JSON_TYPE)
.header("Accept", "application/json")
.header("Authorization", "Basic " +
authStringEnc).header("Content-Type",
"application/json").post(Entity.json(postStr));
/*
* System.out.println("status: " + response.getStatus());
* System.out.println("headers \n: " + response.getHeaders());
* System.out.println("body: \n" +
response.readEntity(String.class));
*/
}
private void sendGet() throws Exception {
String url = URL + getURI;
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
// add request header
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept", "application/json");
con.setRequestProperty("Authorization", "Basic " + authStringEnc);
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
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());
}
private void sendPost() throws Exception {
String url = URL + postURI;
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
// add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
// con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
con.setRequestProperty("Accept", "application/json");
con.setRequestProperty("Authorization", "Basic " + authStringEnc);
String urlParameters = "{\"reply_ids\":\"25ebbf01-5614-4ea6-a4f7-67b752d18ed2\",\"63ed8e18-ecf0-444d-b79e-341e944b0b94\"}";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
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());
}
public static void main(String[] args) throws Exception {
/*
* System.setProperty("http.proxyHost", "");
* System.setProperty("http.proxyPort", "");
*/
APIcall apiCall = new APIcall();
apiCall.getRequest();
apiCall.postRequest();
}
}
If I understand correctly, they want you to convert this into a TestNG test which shouldn't be too difficult as the test and methods are already built. Considering you don't know Java, nor programming, I suggest watching a couple of Youtube videos to get you up to speed on TestNG. I believe once you get your feet wet with TestNG, much of the code along with how to convert it will make more sense.
#Test annotation will behave like a void main for each test (which is a method with the #Test annotation).
You can add a dependency in your maven pom.xml file for junit or testng (any of them will bring this annotation), then, you can trigger the test by running the method from your IDE, or from command line you can simple use:
mvn clean test - to trigger all existent tests
mvn clean test -Dtest=your.package.TestClassName - to trigger tests from a class
mvn clean test -Dtest=your.package.TestClassName#particularMethod - to trigger a specific test
I am currently working on a school project using android. I have java code that sends an HTTP request to a server. It works just find on my laptop using eclipse, but when I try it on my android tablet (an android trio using android 4.4), it does not work. Instead it returns an error (An error occurred while sending the request: in the catch). It is going by the try block and moving to the catch block.
I am attaching the code used for the HTTP request below. I will be leaving out the server information for security reasons. I know the code works, like I said It works on my desktop. Why won't it work with my tablet? Can someone give me a hand with this?
package com.example.tito.profile1;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import android.widget.Toast;
import com.google.gson.Gson;
public class GetUserTest
{
String userName;
public GetUserTest()
{
userName = "Before try";
GetUserRequest request = new GetUserRequest();
request.setSecurityString("Left out for security");
request.setUserId(1);
request.setUserIdToGet(1);
Gson gson = new Gson();
String data = gson.toJson(request);
try
{
URL urlObject = new URL("http://Left out for security");
HttpURLConnection connection = (HttpURLConnection) urlObject.openConnection();
//userName = connection.toString();
connection.setDoInput(true);
connection.setRequestProperty("Content-Type", "application/json");
connection.setConnectTimeout(120000);
connection.setReadTimeout(120000);
connection.setRequestMethod("POST");
connection.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());
wr.write(data);
wr.flush();
wr.close();
if(connection.getResponseCode() == HttpURLConnection.HTTP_OK)
{
InputStream inputStream = connection.getInputStream();
BufferedReader reader = null;
String inputLine;
StringBuilder builder = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(inputStream,"utf-8"));
while ((inputLine = reader.readLine()) != null)
{
builder.append(inputLine);
}
if (reader != null)
{
reader.close();
}
String result = builder.toString();
GetUserResponse response = gson.fromJson(result, GetUserResponse.class);
System.out.println(response.getMessage());
if (response.getSuccess() == true)
{
UserInfo user = response.getUser();
/*System.out.println("UserName: " + user.getUserName());
System.out.println("DisplayName: " + user.getDisplayName());
System.out.println("Description: " + user.getDescription());
System.out.println("Email: " + user.getEmail());
System.out.println("ProductCount: " + user.getProductCount());
System.out.println("FollowedUsers: " + user.getFollowedUsers());
System.out.println("FollowingUsers: " + user.getFollowingUsers());*/
//System.out.println("Join Date:" + user.getCreatedDate());
// userName = "in if statement";
// userName = user.getDisplayName();
}
}
else
{
userName = "error in after else";
//userName = "An error occurred while sending the request: " + connection.getResponseMessage();
}
}
catch (Exception ex)
{
ex.printStackTrace();
userName = "An error occurred while sending the request: in the catch ";
}
}
public String sendBack()
{
return userName;
}
}
I have a problem with my android application. I am trying to make the users fill out a form in the application and send their responses to a Google form online, which would record the responses in a Google spreadsheet. Everything seems fine in the application itself and I encounter no errors there, but only the timestamp shows in the response spreadsheet and no text.
This is my code for the postData method:
public void postData(){
String url = getString(R.string.post_URL);
String name = "testname";
Log.i("test",name);
String lunch = "testlunch";
Log.i("test", lunch);
String vegetarian="testveg";
Log.i("test",vegetarian);
String allergies = "testaler";
Log.i("test",allergies);
String special = "testspec";
Log.i("test",special);
HttpRequest request = new HttpRequest();
try {
String data = R.string.entry_name + URLEncoder.encode(name, "UTF-8") + "&" +
R.string.entry_lunch + URLEncoder.encode(lunch, "UTF-8") + "&" +
R.string.entry_vegetarian + URLEncoder.encode(vegetarian, "UTF-8") + "&" +
R.string.entry_allergies + URLEncoder.encode(allergies, "UTF-8") + "&" +
R.string.entry_special + URLEncoder.encode(special,"UTF-8");
String response = request.sendPost(url,data);
Log.i("response",response);
}
catch(UnsupportedEncodingException e){
Log.d("Unsupported exception", e.toString());
}}
I'm using this URL of the google form:
https://docs.google.com/forms/d/1XPaQe0j86XwcxbO13uxZRawCwUexyJMHdPlPLoQaD1A/formResponse
For the entries, I am using strings formatted like this:
entry.569049980
This is how I call the function (only temporarily):
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Connection().execute();
}
private class Connection extends AsyncTask {
#Override
protected Object doInBackground(Object...arg0){
postData();
return null;
}
The HttpRequest file, which I am using comes from here
import android.util.Log;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
/*
* This helper class was created by StackOverflow user: MattC https://stackoverflow.com/users/21126/mattc
* IT was posted as an Answer to this question: https://stackoverflow.com/questions/2253061/secure-http-post-in-android
*/
public class HttpRequest {
DefaultHttpClient httpClient;
HttpContext localContext;
private String ret;
HttpResponse response = null;
HttpPost httpPost = null;
HttpGet httpGet = null;
public HttpRequest(){
HttpParams myParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(myParams, 10000);
HttpConnectionParams.setSoTimeout(myParams, 10000);
httpClient = new DefaultHttpClient(myParams);
localContext = new BasicHttpContext();
}
public void clearCookies() {
httpClient.getCookieStore().clear();
}
public void abort() {
try {
if (httpClient != null) {
System.out.println("Abort.");
httpPost.abort();
}
} catch (Exception e) {
System.out.println("Your App Name Here" + e);
}
}
public String sendPost(String url, String data) {
return sendPost(url, data, null);
}
public String sendJSONPost(String url, JSONObject data) {
return sendPost(url, data.toString(), "application/json");
}
public String sendPost(String url, String data, String contentType) {
ret = null;
// httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.RFC_2109);
httpClient.getParams().setParameter( ClientPNames.COOKIE_POLICY,
CookiePolicy.NETSCAPE );
httpPost = new HttpPost(url);
response = null;
StringEntity tmp = null;
Log.d("Your App Name Here", "Setting httpPost headers");
httpPost.setHeader("User-Agent", "SET YOUR USER AGENT STRING HERE");
httpPost.setHeader("Accept", "text/html,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*;q=0.5");
if (contentType != null) {
httpPost.setHeader("Content-Type", contentType);
} else {
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
}
try {
tmp = new StringEntity(data,"UTF-8");
} catch (UnsupportedEncodingException e) {
Log.e("Your App Name Here", "HttpUtils : UnsupportedEncodingException : " + e);
}
httpPost.setEntity(tmp);
Log.d("Your App Name Here", url + "?" + data);
try {
response = httpClient.execute(httpPost,localContext);
if (response != null) {
ret = EntityUtils.toString(response.getEntity());
}
} catch (Exception e) {
Log.e("Your App Name Here", "HttpUtils: " + e);
}
Log.d("Your App Name Here", "Returning value:" + ret);
return ret;
}
public String sendGet(String url) {
httpGet = new HttpGet(url);
try {
response = httpClient.execute(httpGet);
} catch (Exception e) {
Log.e("Your App Name Here", e.getMessage());
}
//int status = response.getStatusLine().getStatusCode();
// we assume that the response body contains the error message
try {
ret = EntityUtils.toString(response.getEntity());
} catch (IOException e) {
Log.e("Your App Name Here", e.getMessage());
}
return ret;
}
public InputStream getHttpStream(String urlString) throws IOException {
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try{
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
} catch (Exception e) {
throw new IOException("Error connecting");
} // end try-catch
return in;
}
}
Do I need to use the Drive API or can I make some modifications to make this work? (This seems to be much easier and I am not experienced at all with the Drive API)
You entries format should be "entry_number" and some corrections in your data. Hope this will help you.
String data = "entry_number1lkjhgfdrtyuo=" + URLEncoder.encode(col1) + "&" +
"entry_number2=" + URLEncoder.encode(col2) + "&" +
"entry_number3=" + URLEncoder.encode(col3);
I want to create a java application that automatically logs into a website and does stuff. I'm testing it on my localhost. I'm actually totally new at this and I'm trying to get the concept from http://www.mkyong.com/java/how-to-automate-login-a-website-java-example/ and modifying the code to actually work for my localhost.
package random;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class InternetAutomationPost {
List<String> cookies;
public void setCookies(List<String> cookies) {
this.cookies = cookies;
}
public List<String> getCookies() {
return cookies;
}
private String requestWebPage(String address) {
try {
URL url = new URL(address);
HttpURLConnection con = (HttpURLConnection)url.openConnection();
// Don't use cache. Get a fresh copy.
con.setUseCaches(false);
// Use post or get.
// And default is get.
con.setRequestMethod("GET");
// Mimic a web browser.
con.addRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
con.addRequestProperty("Accept-Encoding", "gzip,deflate,sdch");
con.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
con.addRequestProperty("Connection", "keep-alive");
con.addRequestProperty("User-Agent", "Mozilla/5.0");
if(cookies != null) {
con.addRequestProperty("Cache-Control", "max-age=0");
for (String cookie : this.cookies) {
System.out.print(cookie.split(";", 1)[0]);
con.addRequestProperty("Cookie", cookie.split(";", 1)[0]);
}
}
int responseCode = con.getResponseCode();
System.out.println("\nSending 'GET' request to URL : " + url);
System.out.println("Response Code : " + responseCode);
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while( (inputLine = br.readLine()) != null) {
response.append(inputLine);
}
br.close();
// Get the response cookies
setCookies(con.getHeaderFields().get("Set-Cookie"));
return response.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
private String parsePage(String page) {
Document doc;
try {
doc = Jsoup.parse(page);
Elements form = doc.getElementsByAttributeValue("action", "login.php");
List<String> paramList = new ArrayList<String>();
for(Element loginForm : form) {
System.out.println(loginForm.html());
Elements Input = loginForm.getElementsByTag("input");
for(Element input : Input) {
String name = input.attr("name");
String value = input.attr("value");
if(name.equals("email")) {
value = "admin#admin.com";
} else if(name.equals("password")) {
value = "password";
} else if(name.equals("")) {
continue;
}
paramList.add(name + "=" + URLEncoder.encode(value, "UTF-8"));
}
}
StringBuilder params = new StringBuilder();
for(String values : paramList) {
if(params.length() == 0) {
params.append(values);
} else {
params.append("&" + values);
}
}
System.out.println("Params: " + params);
return params.toString();
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
private void sendPostLogin(String location, String params) {
try {
URL url = new URL(location);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
// Don't use cache. Get a fresh copy.
con.setUseCaches(false);
// Use post or get. We use post this time.
con.setRequestMethod("POST");
// Mimic a web browser.
con.addRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
con.addRequestProperty("Accept-Encoding", "gzip,deflate,sdch");
con.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
con.addRequestProperty("Connection", "keep-alive");
con.addRequestProperty("User-Agent", "Mozilla/5.0");
if(cookies != null) {
con.addRequestProperty("Cache-Control", "max-age=0");
for (String cookie : this.cookies) {
con.addRequestProperty("Cookie", cookie.split(";", 1)[0]);
}
}
con.addRequestProperty("Content-Length", Integer.toString(params.length()));
con.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.addRequestProperty("Host", "localhost");
con.addRequestProperty("Origin", "http://localhost");
con.addRequestProperty("Referrer", "http://localhost/social/index.php");
con.setDoOutput(true);
con.setDoInput(true);
// Write the parameters. Send post request.
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(params);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + params);
System.out.println("Response Code : " + responseCode);
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while( (inputLine = br.readLine()) != null) {
response.append(inputLine);
}
br.close();
// Get the response cookies
setCookies(con.getHeaderFields().get("Set-Cookie"));
System.out.println(response.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* #param args
*/
public static void main(String[] args) {
InternetAutomationPost object = new InternetAutomationPost();
String page = object.requestWebPage("http://localhost/social");
String params = object.parsePage(page);
object.sendPostLogin("http://localhost/social/index.php", params);
}
}
EDIT:
Found out why it sent HTTP response code: 413.
con.addRequestProperty("Content-Length:", Integer.toString(params.length()));
should have been:
con.addRequestProperty("Content-Length", Integer.toString(params.length()));
There was a stray ':'. I've fixed it now.
BUT, still my code doesn't actually login and I still need help .
I have put my full program here now.
I might be wrong but I'm thinking that the params aren't actually getting written to the con.getOutputStream() in the code here:
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(params);
wr.flush();
wr.close();
You set the Content-Length to Integer.toString(params.length())
My guess would be, that your params written as bytes are longer than the Content-Length and your server receives more bytes than expected.
Try:
con.addRequestProperty("Content-Length:", Integer.toString(params.getBytes("UTF-8").length()));
This depends on your encoding obviously. Also have a look at this.